gpt4 book ai didi

java - 计算当前日期和过去日期之间的差异

转载 作者:行者123 更新时间:2023-12-02 11:18:37 26 4
gpt4 key购买 nike

专家,试图在 Android Studio 中显示两个日期之间的差异。已具备以下条件。

下面的第一个条件工作正常。 1.当前日期与 future 日期之间的差异

条件 2 有问题,它显示了值,但没有显示负号以了解其已通过。

  1. 当前日期与过去日期之间的差异。

主要 Activity 。

package com.bar.example.myapplication;

import android.app.DialogFragment;
//import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;


import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

public class MainActivity extends AppCompatActivity {

private EditText editTextDate1, editTextDate2, num1, num2;
private TextView txtResult, tv, textDivNumber, textAVG, txtZaMisiac;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextDate1 = (EditText) findViewById(R.id.editTextDate1);
editTextDate2 = (EditText) findViewById(R.id.editTextDate2);
num1 = (EditText) findViewById(R.id.num1);
num2 = (EditText) findViewById(R.id.num2);
button = (Button) findViewById(R.id.button);
txtResult = (TextView) findViewById(R.id.txtResult);
textDivNumber = (TextView) findViewById(R.id.textDivNumber);
textAVG = (TextView) findViewById(R.id.textAVG);
txtZaMisiac = (TextView) findViewById(R.id.txtZaMisiac);
tv = (TextView) findViewById(R.id.tv);
tv.setText("Current date " + (DateFormat.format("dd.MM.yyyy", new java.util.Date()).toString()));
editTextDate1.setText(DateFormat.format("dd.MM.yyyy", new java.util.Date()).toString());

}

public void diff(View view) {
SimpleDateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
String inputString1 = editTextDate1.getText().toString();
String inputString2 = editTextDate2.getText().toString();
String number11 = num1.getText().toString();
String number12 = num2.getText().toString();

String[] isbnParts = inputString1.split("\\.");
if (Integer.parseInt(isbnParts[0]) > 31) {
Toast.makeText(this, "It looks like you've typed too many days in a month", Toast.LENGTH_SHORT).show();
}
if (Integer.parseInt(isbnParts[1]) > 12) {
Toast.makeText(this, "Gm ... introduced a non-existent month)", Toast.LENGTH_SHORT).show();
}

String[] isbnParts1 = inputString2.split("\\.");
if (Integer.parseInt(isbnParts1[0]) > 31) {
Toast.makeText(this, "Hey ... too many days in a month", Toast.LENGTH_SHORT).show();
}
if (Integer.parseInt(isbnParts1[1]) > 12) {
Toast.makeText(this, "Hmm ... you entered a non-existent month)", Toast.LENGTH_SHORT).show();
}

if (inputString1.matches("") || inputString2.matches("")) {
Toast.makeText(this, "No dates entered", Toast.LENGTH_SHORT).show();
} else {

try {
Date date1 = myFormat.parse(inputString1);
Date date2 = myFormat.parse(inputString2);
long diffDate = Math.abs(date2.getTime() - date1.getTime());
txtResult.setText("" + TimeUnit.DAYS.convert(diffDate, TimeUnit.MILLISECONDS));

} catch (ParseException e) {
e.printStackTrace();
}
if (number11.matches("") || number12.matches("")) {
Toast.makeText(this, "No numbers entered for calculation", Toast.LENGTH_SHORT).show();
} else {

String pattern = "##0.00";
String pattern1 = "##0";
DecimalFormat decimalFormat = new DecimalFormat(pattern);
DecimalFormat decimalFormat1 = new DecimalFormat(pattern1);

float number1 = Integer.parseInt(number11);
float number2 = Integer.parseInt(number12);
float diffDateInt = Integer.parseInt(txtResult.getText().toString());
float diffnumb = Math.abs(number1 - number2);
String format3 = decimalFormat1.format(diffnumb);
textDivNumber.setText(String.valueOf(format3));
String format = decimalFormat.format((diffnumb / diffDateInt) * 30.00);
txtZaMisiac.setText(String.valueOf(format));
String format1 = decimalFormat.format(diffnumb / diffDateInt);
textAVG.setText(String.valueOf(format1));
}
}
}

public void setDate1(View view) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "Date Picker");
}
public void setDate2(View view) {
DialogFragment newFragment = new DatePickerFragment2();
newFragment.show(getFragmentManager(), "Date Picker");
}
}

DatePickerFragment.java

package com.bar.example.myapplication;

import android.app.DatePickerDialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.DatePicker;
import android.app.Dialog;
import java.util.Calendar;

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
EditText editTextDate1 = (EditText) getActivity().findViewById(R.id.editTextDate1);
String stringOfDate = day + "." + (month + 1) + "." + year;
editTextDate1.setText(stringOfDate);
}
}

DatePickerFragment2.java

package com.bar.example.myapplication;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.EditText;


import java.util.Calendar;

public class DatePickerFragment2 extends DialogFragment implements DatePickerDialog.OnDateSetListener {

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
EditText editTextDate2 = (EditText) getActivity().findViewById(R.id.editTextDate2);
String stringOfDate = day + "." + (month + 1) + "." + year;
editTextDate2.setText(stringOfDate);
}
}

布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:background="#B3E5FC"
tools:context=".MainActivity"
>
<!--This example works only date picker mode = spinner mode only-->
<!--DatePicker with spinner and without Calendar-->
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="set date 1"
android:id="@+id/btnDate1" android:layout_alignParentTop="true" android:layout_alignParentLeft="true"
android:layout_marginTop="42dp" android:onClick="setDate1"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="set date 2"
android:id="@+id/btnDate2" android:layout_alignTop="@+id/btnDate1" android:layout_alignParentRight="true"
android:onClick="setDate2"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="calculate"
android:id="@+id/button"
android:onClick="diff" android:layout_centerVertical="true" android:layout_centerHorizontal="true"
android:textColor="#f21124"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editTextDate1" android:layout_below="@+id/btnDate1" android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/btnDate1"
android:inputType="date" android:textColor="#9e0e1f" android:textSize="15dp"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editTextDate2" android:layout_below="@+id/btnDate2"
android:layout_alignRight="@+id/btnDate2" android:layout_alignLeft="@+id/btnDate2"
android:inputType="date" android:textColor="#e11515" android:textSize="15dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/txtResult"
android:text="............"
android:textSize="14dp" android:layout_below="@+id/button" android:layout_alignLeft="@+id/num2"
android:layout_alignStart="@+id/num2" android:textColor="#5c2e2e"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/num1" android:layout_below="@+id/editTextDate1" android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_toStartOf="@+id/button" android:layout_alignRight="@+id/editTextDate1"
android:layout_alignEnd="@+id/editTextDate1" android:textColor="#590e9b" android:textSize="15dp"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="number"
android:ems="10"
android:id="@+id/num2" android:layout_below="@+id/editTextDate2" android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" android:layout_alignLeft="@+id/editTextDate2"
android:layout_alignStart="@+id/editTextDate2" android:textColor="#3818ad" android:textSize="15dp"/>

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/txtResult"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:text="Between dates"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#060606"
android:textSize="14dp" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/textView"
android:text="The difference between the numbers"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#070707"
android:textSize="14dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="............"
android:id="@+id/textDivNumber"
android:layout_below="@+id/txtResult" android:layout_alignLeft="@+id/txtResult"
android:layout_alignStart="@+id/txtResult" android:textColor="#782f2f" android:textSize="14dp"/>

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="@+id/textView2"
android:text="Average value"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#0a0a0a"
android:textSize="14dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="............"
android:id="@+id/textAVG"
android:layout_below="@+id/textDivNumber" android:layout_alignLeft="@+id/textDivNumber"
android:layout_alignStart="@+id/textDivNumber" android:textColor="#7e3333" android:textSize="14dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="@+id/tv"
android:layout_alignParentTop="true" android:layout_centerHorizontal="true"/>

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textDivNumber"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:text="days"
android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
android:id="@+id/textView5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView3"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_alignStart="@+id/textView3"
android:layout_below="@+id/textDivNumber"
android:text="in a day"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="10dp" />

<TextView
android:id="@+id/textView6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignTop="@+id/txtZaMisiac"
android:text="Per month"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#171414"
android:textSize="14dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="............"
android:id="@+id/txtZaMisiac"
android:layout_below="@+id/textView5" android:layout_alignLeft="@+id/textAVG"
android:layout_alignStart="@+id/textAVG" android:textSize="14dp" android:textColor="#052df7"/>
</RelativeLayout>

第一个条件运行良好(当前日期与 future 日期)。下面的截图。 enter image description here

第二个条件(当前日期与过去日期)显示值而不是负值 -29。 enter image description here

新的差异代码

public void diff(View view) {

// SimpleDateFormat myFormat = new SimpleDateFormat("dd.MM.yyyy");
// String inputString1 = ok.getText().toString();
// String inputString2 = ok1.getText().toString();
CharSequence inputString1 = editTextDate1.getText();

try {
LocalDate date1 = LocalDate.parse(inputString1, dateFormatter);
CharSequence inputString2 = editTextDate2.getText();
try {
LocalDate date2 = LocalDate.parse(inputString2, dateFormatter);
long diffDate = ChronoUnit.DAYS.between(date1, date2);
txtResult.setText(String.valueOf(diffDate));
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date2 is not a valid date: " + inputString2, Toast.LENGTH_SHORT).show();
}
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date1 is not a valid date: " + inputString1, Toast.LENGTH_SHORT).show();
}
// if (number11.matches("")||number12.matches("")){Toast.makeText(this, "No numbers entered for calculation", Toast.LENGTH_SHORT).show();}

}

最佳答案

java.time

我们首先声明一个格式化程序。这可能是一个静态字段:

private static DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d.M.uuuu");

然后在 MainActivity 中的 diff 方法中,您可以执行以下操作:

    CharSequence inputString1 = editTextDate1.getText();
try {
LocalDate date1 = LocalDate.parse(inputString1, dateFormatter);
CharSequence inputString2 = editTextDate2.getText();
try {
LocalDate date2 = LocalDate.parse(inputString2, dateFormatter);
long diffDate = ChronoUnit.DAYS.between(date1, date2);
txtResult.setText(String.valueOf(diffDate));
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date2 is not a valid date: " + inputString2, Toast.LENGTH_SHORT).show();
}
} catch (DateTimeParseException dtpe) {
Toast.makeText(this, "Date1 is not a valid date: " + inputString1, Toast.LENGTH_SHORT).show();
}
  • 如果日期是 5.5.201831.5.2018,则显示差异 26
  • 如果日期是 5.5.20181.5.2018,则显示差异 -4

您的代码出了什么问题?

我相信这一行是罪魁祸首:

        long diffDate = Math.abs(date2.getTime() - date1.getTime());

Math.abs() 取参数的绝对值,即将负数转换为正数。因此,无论日期是过去还是将来,您都会在这里得到一个正数。从毫秒转换为天后,您仍然有一个正数,因此它显示时没有符号。

也就是说,您使用的日期和时间类 CalendarDateSimpleDateFormat 早已过时且设计不佳。 SimpleDateFormat 尤其是出了名的麻烦。考虑避免它们并使用现代 Java 日期和时间 API java.time

问题:我可以在 Android 上使用 java.time 吗?

是的,java.time 在旧版和新版 Android 设备上都能很好地工作。它只需要至少 Java 6

  • 在 Java 8 及更高版本以及新的 Android 设备(据我所知,从 API 级别 26 开始)中,新的 API 是内置的。
  • 在 Java 6 和 7 中获取 ThreeTen Backport,即新类的向后移植(ThreeTen for JSR 310,其中首次描述了现代 API)。
  • 在(较旧的)Android 上,使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。确保从包 org. Threeten.bp 和子包中导入日期和时间类。

链接

关于java - 计算当前日期和过去日期之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084924/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com