toString() returns 日期对象上的意外事件

toString() returns unexpected things on a Date object

我最近开始使用 Android Studio 3.1.2 和 SDK 19 编写我真正的第一个 Android 项目。

我的一个对象具有日期属性。在某些时候,我想在 TextView 中显示整个日期时间或其中的一部分。所以我以新手的方式尝试了它,并在我的日期上调用了 toString() 。 但是,显示的文本包含我未在用于创建日期对象的 SingleDateFormat 模式中定义的元素。

这就是我在 myObject 上创建日期的方式:

Date date1;
Date date2;

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

try {
    date1 = format.parse(json.getString("date_1"));
    dtae2 = format.parse(json.getString("date_2"));
} catch(ParseException e) {
    //error handling stuff
    e.printStackTrace();
}

这是我要在视图上显示日期的位置:

myTextView.setText("First appearance logged at " + myObject.getDate1().toString());

我希望显示像 2018-08-16 12:14:42 这样的字符串。相反,我得到的是 Thu Aug 12:14:42 GMT +02:00 2018。这似乎是另一个 DateFormat 并忽略了我的自定义模式。

所以我的问题是,如果有一种方法可以操纵 toString() 的输出,那么日期就会按照我在模式中定义的方式显示。我能以某种方式将模式传递给 toString() 方法吗?

编辑

我将 Objects 的属性更改为 String 类型,尽管这样更容易呈现。将它们转换为日期的原因是,我需要计算两个人之间的持续时间,但这不是我无法解决的问题。感谢社区。

您需要使用 SimpleDateFormat 这样的东西:

String myFormat = "yyyy-MM-dd HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
myTextView.setText("First appearance logged at " + sdf.format(date1));

根据您的需要,您可以只使用json.getString("date_1")

您不需要设置额外的逻辑。当您想将 String 日期转换为 Date 对象进行某些计算时,需要进行解析。

如果您想更改接收日期的格式,请使用此方法。

changeStringDateFormat(json.getString("date_1"), "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd");

只需将此方法放入您的 Util 中即可。

public String changeStringDateFormat(String date, String inputDateFormat, String outPutDateFormat) {
    Date initDate = null;
    try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(inputDateFormat);
        initDate = simpleDateFormat.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    SimpleDateFormat outputFormatter = new SimpleDateFormat(outPutDateFormat);
    String parsedDate = outputFormatter.format(initDate);
    return parsedDate;
}

请参阅 Java Date Doc,它 returns 默认格式的字符串。

public String toString()

Converts this Date object to a String of the form:

dow mon dd hh:mm:ss zzz yyyy

简单写下这段代码

JAVA 文件

 public class MainActivity extends AppCompatActivity {
    TextView my_text;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        my_text = findViewById(R.id.my_text);

        String pattern = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        String date = simpleDateFormat.format(new Date());
        Toast.makeText(getApplicationContext(), "" + date, Toast.LENGTH_SHORT).show();
        my_text.setText("Your Date is :  " + date);
    }
}

XML 文件

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="mydemo.com.anew.MainActivity">

    <TextView
        android:id="@+id/my_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

查看输出:

查看与您的要求相同的输出屏幕截图获取当前日期:

参考这个Tutorial

希望对您有所帮助

在我的项目中,我一直在使用 format() 函数进行格式化,如下所示:

myTextView.setText("First appearance logged at " + format.format(myObject.getData1()));

希望对您有所帮助。

tl;博士

使用现代的 java.time classes 而不是可怕的遗产 Date & SimpleDateFormat class es.

myJavaUtilDate          // Never use `java.util.Date`.
.toInstant()            // Convert from legacy class to modern replacement. Returns a `Instant` object, a moment in UTC.
.atOffset(              // Convert from the basic `Instant` class to the more flexible `OffsetDateTime` class.
    ZoneOffset.UTC      // Constant defining an offset-from-UTC of zero, UTC itself.
)                       // Returns a `OffsetDateTime` object.
.format(                // Generate a `String` with text representing the value of this `OffsetDateTime` object.
    DateTimeFormatter.ISO_LOCAL_DATE_TIME  // Pre-defined formatter stored in this constant. 
)                       // Returns a `String` object.
.replace( "T" , " " )   // Replace the standard `T` in the middle with your desired SPACE character.

2018-08-16 10:14:42

java.time

您正在使用可怕的旧 classes,这些 classes 多年前被 java.time classes.

取代

如果递给一个java.util.Date对象,立即转换为java.time.Instant。两者都代表 UTC 中的一个时刻。 Instant 具有比毫秒更精细的纳秒分辨率。

要在传统 classes 和现代 classes 之间转换,请查看添加到旧 classes 的新转换方法。

Instant

Instant instant = myJavaUtilDate.toInstant() ;  // New method on old class for converting to/from java.time classes.

ISO 8601

要生成 String 文本的标准 ISO 8601 格式类似于您想要的格式,请调用 toString

String output = instant.toString() ;  // Generate text in standard ISO 8601 format.

经过的时间 = Duration

顺便说一下,要计算运行时间,请使用 Duration classes。传递一对 Instant 对象来计算经过的 24 小时 "days"、小时、分钟和秒数。

Duration d = Duration.between( start , stop ) ;  // Calc elapsed time.

2018-08-16T10:14:42Z

OffsetDateTime

对于其他格式,从基本的 Instant class 转换为更灵活的 OffsetDateTime class。

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC ) ;

odt.toString(): 2018-08-16T10:14:42Z

DateTimeFormatter

您想要的格式接近于预定义的格式 DateTimeFormatter.ISO_LOCAL_DATE_TIME。只需将中间的 T 替换为 SPACE。

String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " ) ;

2018-08-16 10:14:42

ZonedDateTime

请记住,到目前为止我们只关注 UTC。对于任何给定的时刻,日期和时间都在全球范围内因地区而异。

如果你想通过某个地区(一个时区)人们使用的挂钟时间的镜头看到同一时刻,那么应用 ZoneId 得到 ZonedDateTime对象。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

zdt.toString(): 2018-08-16T11:14:42+01:00[Africa/Tunis]

您可以使用与上面相同的格式化程序来生成所需格式的字符串。

String output = zdt.format( f ) ;

关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* classes.

在哪里获取java.time classes?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.