日期差异为 0。如何(算法)使用 EditView 中的日期?

Date difference is 0. How to (aritmethic) work with Date(s) from EditView(s)?

我现在用这段代码工作了大约 12 个小时,但仍然无法正常工作。 免责声明:我正在使用日期 - 不是日历,也不是 Instant- 因为我正在编码 API 15(我的智能手机)。

这就是我想要做的:

我有几个用户可以在其中编写的 EditView。范例

EditText StartDateEditText = (EditText) findViewById(R.id.getStartDate_editText);
EditText EndDateEditText = (EditText) findViewById(R.id.getEndDate_editText);
EditText StartHourEditText = (EditText) findViewById(R.id.getStartHour_editText);

我需要恢复该信息(字符串)并将其转换为 date/time。示例:

SimpleDateFormat StartFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
        String StartAssembled = StartDateToString + " " + StartTimeToString;
        Date StartMoment = null;
        try {
            StartMoment = StartFormat.parse(StartAssembled);
        } catch (ParseException e) {
            e.printStackTrace();
        }

最后,我需要找到经过的时间并显示它:

long difference = EndMoment.getTime() - StartMoment.getTime();
long differenceSeconds = difference / 1000;
long differenceMinutes = differenceSeconds % 60;
long differenceHours = differenceSeconds % (60 * 60);
String differenceToString = "Hours: " + String.valueOf(differenceHours) +
        " Minutes: " + String.valueOf(differenceMinutes) +
        " Seconds: " + String.valueOf(differenceSeconds);
Log.v("MainActivity:", differenceToString);

现在,用户输入_ 2017 年 9 月 29 日开始 12:01 2017 年 9 月 29 日结束 16:31

然后我得到...

09-29 15:23:54.213 7798-7798/com.example.android.timeismoney V/MainActivity: Hours: 0 Minutes: 0 Seconds: 0

顺便说一句:StartJobDate - EndJobDate 也同样冗长

但它应该记录:小时:4 分钟:30 秒:0

我是 java 的新手,也是时间管理的新手。将不胜感激任何帮助。有什么建议或提示可以做得更好吗?


下面,我复制并评论我的代码:

进口等:

package com.example.android.timeismoney;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

方法命名为"cosa"(英文"thing")因为是我的游乐场。从 xml.

中的按钮中的 onClick 调用
public void cosa(View view) {

从这里我关注 EditText(s)

    EditText StartDateEditText = (EditText) findViewById(R.id.getStartDate_editText);
    EditText EndDateEditText = (EditText) findViewById(R.id.getEndDate_editText);
    EditText StartHourEditText = (EditText) findViewById(R.id.getStartHour_editText);
    EditText StartMinuteEditText = (EditText) findViewById(R.id.getStartMinute_editText);
    EditText EndHourEditText = (EditText) findViewById(R.id.getEndHour_editText);
    EditText EndMinuteEditText = (EditText) findViewById(R.id.getEndMinute_editText);

现在我恢复文本

String StartDateToString = StartDateEditText.getText().toString();
String StartTimeToString = StartHourEditText.getText().toString() +
               ":" + StartHourEditText.getText().toString();
String EndDateToString = EndDateEditText.getText().toString();
String EndTimeToString = EndHourEditText.getText().toString() +
               ":" + EndHourEditText.getText().toString();

这里我设置了日期变量并用来自 EditText(s) 的数据填充它们

SimpleDateFormat StartFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String StartAssembled = StartDateToString + " " + StartTimeToString;
Date StartMoment = null;
try {
    StartMoment = StartFormat.parse(StartAssembled);
} catch (ParseException e) {
    e.printStackTrace();
}

SimpleDateFormat EndFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String EndAssembled = EndDateToString + " " + EndTimeToString;
Date EndMoment = null;
try {
    EndMoment = EndFormat.parse(EndAssembled);
} catch (ParseException e) {
    e.printStackTrace();
}

现在我操作得到毫秒。我转换它们。然后,给他们看。

    long difference = StartMoment.getTime() - EndMoment.getTime();
    long differenceSeconds = difference / 1000;
    long differenceMinutes = difference / (60 * 1000);
    long differenceHours = difference / (1000 * 60 * 60);
    String differenceToString = "Hours: " + String.valueOf(differenceHours) +
            " Minutes: " + String.valueOf(differenceMinutes) +
            " Seconds: " + String.valueOf(differenceSeconds);
    Log.v("MainActivity:cosa()", differenceToString);


}

这是我的全部 MainActivity.java:https://github.com/Hinuden/ShowAndTell/commits/master/TimeIsMoney29-09-2017-MainActivity.java

这是我的全部activity_main.xml:https://github.com/Hinuden/ShowAndTell/blob/master/TimeIsMoney-29-09-2017-activity_main.xml

感谢您的帮助。

我真的不知道这里发生了什么黑魔法。由于你们大多数人报告代码有效,我只能得到零。

但是甘道夫以 JIWILS 的身份前来帮助,他写道:

When you create the differenceToString you don't need to call String.valueOf. You can just concatenate like this: String differenceToString = "Hours: " + differenceHours + " Minutes: " + differenceMinutes + " Seconds: " + differenceSeconds; – jwils 1 hour ago

我改变了这个:

String differenceToString = "Hours: " + String.valueOf(differenceHours) +
            " Minutes: " + String.valueOf(differenceMinutes) +
            " Seconds: " + String.valueOf(differenceSeconds);

为此:

String differenceToString = "Hours: " + differenceHours +
                " Minutes: " + differenceMinutes +
                " Seconds: " + differenceSeconds;

而且效果很好。问题出在哪里?完全不知道。但它有效。

另外我重写了这样的算法:

long difference = EndMoment.getTime() - StartMoment.getTime();
        long differenceHours = difference / (1000 * 60 * 60);
        long differenceMinutes = (difference % (1000 * 60 * 60)) / (1000 * 60);
        long differenceSeconds = ((difference % (1000 * 60 * 60)) % (1000 * 60)) / 1000;

现在完美显示了开始和结束之间的区别。

我已经测试了你的代码,并没有在输出中得到零:

SimpleDateFormat f = new SimpleDateFormat("dd/MM/yyyy HH:mm");
Date start = f.parse("29/09/2017 12:01");
Date end = f.parse("29/09/2017 16:31");
long difference = (end.getTime() - start.getTime());
// ... same code as yours

相反,我得到了这个输出:

Hours: 4 Minutes: 270 Seconds: 16200

我没有得到零,但无论如何,你计算值的方式有问题。您将获得相当于 秒数,而不是将其分解为每个时间单位。你应该这样做:

long differenceSeconds = (end.getTime() - start.getTime()) / 1000;
long differenceHours = differenceSeconds / 3600;
// discount the total hours
differenceSeconds -= (differenceHours * 3600);
long differenceMinutes = differenceSeconds / 60;
// discount the total seconds
differenceSeconds -= (differenceMinutes * 60);

现在 differenceToString 的值将是:

Hours: 4 Minutes: 30 Seconds: 0


备注:

  • 由于输入只有小时和分钟,您可以舍弃秒(它们始终为零),因此您也可以直接从分钟进行计算。
  • 您不需要使用 String.valueOf。当您将数字与 String 连接时,只需直接使用其值
  • 正如您从上面注意到的,我使用了相同的 SimpleDateFormat 实例,因为开始日期和结束日期的格式相同。

所以你的计算应该是这样的:

long differenceMinutes = (end.getTime() - start.getTime()) / 1000 / 60;
long differenceHours = differenceMinutes / 60;
// discount the number of hours
differenceMinutes -= (differenceHours * 60);
// seconds is always zero, because I'm not considering in the input
String differenceToString = "Hours: " + differenceHours + " Minutes: " + differenceMinutes + " Seconds: 0";

乔达时间

我通常会建议 ThreeTen Backport, but it works only with JDK 6 and 7, so for JDK 5 you could use Joda-Time,一个很好的 API 来处理 date/time 东西。

首先,您使用 org.joda.time.format.DateTimeFormat 和所需的模式创建 org.joda.time.format.DateTimeFormatter。然后我将输入解析为 org.joda.time.DateTime 并使用 org.joda.time.Period 计算日期之间的差异。

那我可以直接用Period或者用一个org.joda.time.format.PeriodFormatter来格式化区别:

// parse dates
DateTimeFormatter f = DateTimeFormat.forPattern("dd/MM/yyyy HH:mm");
DateTime start = f.parseDateTime("29/09/2017 12:01");
DateTime end = f.parseDateTime("29/09/2017 16:31");
// calculate difference
Period diff = new Period(start, end);

String differenceToString = "Hours: " + diff.getHours() + " Minutes: " + diff.getMinutes() + " Seconds: " + diff.getSeconds();
System.out.println(differenceToString);

输出将是:

Hours: 4 Minutes: 30 Seconds: 0

我也可以用 PeriodFormatter:

PeriodFormatter pf = new PeriodFormatterBuilder()
    // hours
    .appendPrefix("Hours: ").appendHours()
    // optional space (if there are more fields)
    .appendSeparatorIfFieldsBefore(" ")
    // minutes
    .appendPrefix("Minutes: ").appendMinutes()
    // optional space (if there are more fields)
    .appendSeparatorIfFieldsBefore(" ")
    // seconds
    .appendPrefix("Seconds: ").appendSeconds()
    // create formatter
    .toFormatter();
System.out.println(pf.print(diff));

不同之处在于,如果值为零,它会忽略秒数:

Hours: 4 Minutes: 30