java - 使用simpleDateFormat java解析日期
问题描述
我想将字符串解析为日期,但获得的日期不正确。我的代码是这样的:
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
我需要约会:* 2019 年 12 月 17 日 17:40:39
解决方案
的SimpleDateFormat
精度不超过毫秒 ( .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 及其格式化 APISimpleDateFormat
已过时且容易出错。建议完全停止使用它们并切换到现代日期时间 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: Date Time了解有关现代日期时间 API 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和 Android API 工作level 仍然不符合 Java-8,请检查Java 8+ APIs available through desugaring和How to use ThreeTenABP in Android Project。
推荐阅读
- java - ArrayoutofBounds 发现异常无法解决
- r - 如何在 Ggplot2 标签中使用“符号 = 数字”和“字符 = 数字”
- java - 为什么 java 编译器需要一个看似无用的包装函数来类型检查泛型边界?
- r - 在R中绘制小提琴图
- reactjs - Redux-Toolkit 查询授权案例
- javascript - 输入装饰器在 Angular 中不起作用(属性“名称”没有初始值设定项,并且未在构造函数中明确分配。)
- angularjs - 如何在具有溢出属性的 div 中显示完整的工具提示(未裁剪)?
- c# - 从文件中删除文本
- android - com.fyber:fyber-sdk:8.22.1 没有缓存版本可用于离线模式
- amazon-web-services - 尝试使用 codepipeline 将 spring boot + mysql 应用程序部署到 AWS 时出错