将字符串转换为带毫秒的日期

huangapple go评论80阅读模式
英文:

Convert String to Date with Milliseconds

问题

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);

输出:

Thu Aug 27 10:06:07 WAT 2020

我希望结果是 Date 类型的。

英文:

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:

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

答案1

得分: 3

Date类以毫秒为单位存储时间,如果您查看日期对象,您会发现它实际上的时间为1598515567413毫秒。

您被System.out.println()欺骗了,它使用了Date的toString()方法。该方法使用"EEE MMM dd HH:mm:ss zzz yyyy"格式显示日期,并简单地省略了所有毫秒。

如果您使用带有毫秒的格式化程序,该格式化程序的格式字符串中包含毫秒,您会看到毫秒是正确的:

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

输出结果为:2020-08-27T10:06:07.413

英文:

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.

You are fooled by the System.out.println() which uses Date's toString() method. This method is using the "EEE MMM dd HH:mm:ss zzz yyyy" format to display the date and simply omits all milliseconds.

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

答案2

得分: 2

你可以使用:

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);

或者你也可以使用 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"));

// 然后你可以根据需要使用对象 ldate。
英文:

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:

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.

答案3

得分: 2

更新(基于楼主的评论):

你提到了:谢谢,非常有帮助。我已经尝试过 java.util,但我无法使用 LocalDateTime 在数据库中设置日期,这就是为什么我在使用 Date

你需要使用 PreparedStatement#setObjectLocalDate 设置到数据库表中,示例如下:

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

原始答案:

以下是 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();
}

正如你在这个实现中看到的,它不包括 毫秒 部分。因此,如果你按照以下代码打印 date,你将得到 Date#toString 返回的内容,因此输出中不会显示 毫秒

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);

我假设你已经知道 System.out.println(obj) 会打印 obj.toString() 返回的字符串。

如何以自定义格式获得输出?

你有两个选项:

  1. 推荐选项:使用日期时间格式化器,例如 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. 通过扩展 java.util.Date 创建一个自定义类,重写 DatetoString 实现。尽管这是一个选项,但我不建议这样做。

最后,一些建议:

停止使用过时且容易出错的 java.util 日期时间 API 和 SimpleDateFormat。转而使用现代的 java.time 日期时间 API 以及相应的格式化 API (java.time.format)。从**教程:日期时间**中了解更多关于现代日期时间 API 的信息。

英文:

Update (based on OP's comment):

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

You've to use PreparedStatement#setObject to set LocalDate into the database table e.g.

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:

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.

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().

How can you get output in a custom format?

You have two options:

  1. Recommended option: Use a date-time formatter e.g. SimpleDateFormat as shown below:

    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. 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. Switch to the modern java.time date-time API and the corresponding formatting API (java.time.format). Learn more about the modern date-time API from Trail: Date Time.

huangapple
  • 本文由 发表于 2020年8月28日 17:27:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63631068.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定