简体   繁体   English

以毫秒为单位将字符串转换为日期

[英]Convert String to Date with Milliseconds

I know that there many subject of how to convert from String to Date, I'm using 'SimpleDateFormat' and i have a string that contains (Year, Month, Day , Hour, Minute, second, Milliseconds) but when I'm using the 'SimpleDateFormat' the Milliseconds is not set here the code and the output:我知道有很多关于如何从字符串转换为日期的主题,我使用的是“SimpleDateFormat”,我有一个包含(年、月、日、小时、分钟、秒、毫秒)的字符串,但是当我使用'SimpleDateFormat' 毫秒未在此处设置代码和输出:

import java.text.SimpleDateFormat;
import java.util.Date;

String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date dateFormatter = formatter.parse(strDate);

System.out.println(dateFormatter);

Output:输出:

Thu Aug 27 10:06:07 WAT 2020

I want the result in type Date我想要日期类型的结果

The Date class stores the time as milliseconds, and if you look into your date object you will see that it actually has a time of 1598515567413 milliseconds. Date 类以毫秒为单位存储时间,如果你查看你的日期对象,你会发现它实际上有 1598515567413 毫秒的时间。

You are fooled by the System.out.println() which uses Date's toString() method.您被使用 Date 的 toString() 方法的 System.out.println() 愚弄了。 This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.此方法使用“EEE MMM dd HH:mm:ss zzz yyyy”格式来显示日期并简单地省略所有毫秒。

If you use your formatter, which has milliseconds in its format string, you will see that the milliseconds are correct:如果您使用格式字符串中包含毫秒的格式化程序,您将看到毫秒是正确的:

System.out.println(formatter.format(dateFormatter));

outputs 2020-08-27T10:06:07.413输出 2020-08-27T10:06:07.413

You can use:您可以使用:

String strDate = "2020-08-27T10:06:07.413"

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS");
DateTime datetimeDF = formatter.parseDateTime(strDate);
String text = formatter.print(datetimeDF);

System.out.println(text);

Or you can use java.time :或者你可以使用java.time

String strDate = "2020-08-27T10:06:07.413"
LocalDateTime ldate = LocalDateTime.parse(datetime, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"));

and use the object ldate as you want.并根据需要使用对象ldate

Update (based on OP's comment ):更新(基于 OP 的评论):

You have mentioned : Thanks that was realy heplful I've allready tried the java.util but i could not set the date in the database using LocalDateTime that's why I'm using Date您已经提到:谢谢,这真的非常有用我已经尝试过 java.util,但是我无法使用 LocalDateTime 在数据库中设置日期,这就是我使用 Date 的原因

You've to use PreparedStatement#setObject to set LocalDate into the database table eg您必须使用PreparedStatement#setObjectLocalDate设置到数据库表中,例如

LocalDate localDate = LocalDate.now();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, localDate);
st.executeUpdate(); 
st.close();

Original answer:原答案:

Given below is the toString implementation of java.util.Date :下面给出的是java.util.DatetoString实现:

public String toString() {
    // "EEE MMM dd HH:mm:ss zzz yyyy";
    BaseCalendar.Date date = normalize();
    StringBuilder sb = new StringBuilder(28);
    int index = date.getDayOfWeek();
    if (index == BaseCalendar.SUNDAY) {
        index = 8;
    }
    convertToAbbr(sb, wtb[index]).append(' ');                        // EEE
    convertToAbbr(sb, wtb[date.getMonth() - 1 + 2 + 7]).append(' ');  // MMM
    CalendarUtils.sprintf0d(sb, date.getDayOfMonth(), 2).append(' '); // dd

    CalendarUtils.sprintf0d(sb, date.getHours(), 2).append(':');   // HH
    CalendarUtils.sprintf0d(sb, date.getMinutes(), 2).append(':'); // mm
    CalendarUtils.sprintf0d(sb, date.getSeconds(), 2).append(' '); // ss
    TimeZone zi = date.getZone();
    if (zi != null) {
        sb.append(zi.getDisplayName(date.isDaylightTime(), TimeZone.SHORT, Locale.US)); // zzz
    } else {
        sb.append("GMT");
    }
    sb.append(' ').append(date.getYear());  // yyyy
    return sb.toString();
}

As you can see in this implementation, it doesn't include milliseconds and therefore if you print date as in the following code, you will get what the Date#toString returns and thus, you won't see milliseconds in the output.正如你在这个实现中看到的,它不包括milliseconds ,因此如果你在下面的代码中打印date ,你将得到Date#toString返回的内容,因此你不会在输出中看到milliseconds

String strDate = "2020-08-27T10:06:07.413";
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date= formatter.parse(strDate);
System.out.println(date);

I assume that you already know that System.out.println(obj) prints the string returned by obj.toString() .我假设您已经知道System.out.println(obj)打印obj.toString()返回的字符串。

How can you get output in a custom format?如何获得自定义格式的输出?

You have two options:您有两个选择:

  1. Recommended option: Use a date-time formatter eg SimpleDateFormat as shown below:推荐选项:使用日期时间格式化程序,例如SimpleDateFormat ,如下所示:

     String strDate = "2020-08-27T10:06:07.413"; SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS"); Date date = formatter.parse(strDate); System.out.println(date); String dateStr = formatter.format(date); System.out.println(dateStr);
  2. Override toString implementation of Date by creating a custom class by extending java.util.Date .通过扩展java.util.Date创建自定义类来覆盖DatetoString实现。 Although it's an option, I never recommend this to do.尽管这是一种选择,但我从不建议这样做。

Finally, a piece of advice:最后,给一个忠告:

Stop using the outdated and error-prone java.util date-time API and SimpleDateFormat .停止使用过时且容易出错的java.util date-time API 和SimpleDateFormat Switch to the modern java.time date-time API and the corresponding formatting API ( java.time.format ).切换到现代java.time日期时间 API 和相应的格式化 API ( java.time.format )。 Learn more about the modern date-time API from Trail: Date Time .Trail: Date Time 中了解有关现代日期时间 API 的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM