使用simpleDateFormat java解析日期 [英] parsing date using simpleDateFormat java
问题描述
我想将字符串解析为日期,但获取的日期不正确.我的代码就像:
I want to parse an String to Date but the date obtained is incorrect. my code is like :
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.S a");
date1 = df.parse("17-DEC-19 05.40.39.364000000 PM");
但 date1 是:Sat Dec 21 22:47:19 IRST 2019
but date1 is: Sat Dec 21 22:47:19 IRST 2019
我需要约会:* 2019 年 12 月 17 日 17:40:39 IRST
I need to date: * Dec 17 17:40:39 IRST 2019
推荐答案
SimpleDateFormat
的精度不能超过毫秒 (.SSS
).
The SimpleDateFormat
does not have precision beyond milliseconds (.SSS
).
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSS a", Locale.ENGLISH);
Date date1 = df.parse("17-DEC-19 05.40.39.364 PM");
System.out.println(date1);
}
}
输出:
Tue Dec 17 17:40:39 GMT 2019
请注意,java.util
日期时间 API 及其格式化 API SimpleDateFormat
已过时且容易出错.建议完全停止使用它们并切换到 现代日期时间 API* .
Note that the java.util
date-time API and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API* .
使用现代日期时间 API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter df = new DateTimeFormatterBuilder()
.parseCaseInsensitive() // For case-insensitive (e.g. AM/am) parsing
.appendPattern("dd-MMM-yy hh.mm.ss.n a")
.toFormatter(Locale.ENGLISH);
LocalDateTime ldt = LocalDateTime.parse("17-DEC-19 05.40.39.364000000 PM", df);
System.out.println(ldt);
}
}
输出:
2019-12-17T17:40:39.364
从 Trail 了解有关现代日期时间 API 的更多信息:日期时间.
Learn more about the modern date-time API from Trail: Date Time.
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport 将大部分 java.time 功能向后移植到 Java 6 &7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ API 可通过 desugaring 和 如何在 Android 项目中使用 ThreeTenABP.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
这篇关于使用simpleDateFormat java解析日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!