我想获取当前系统时间,然后通过格式化程序解析它 SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
.
我得到 .... error : java.text.ParseException: Unparseable date: "Tue Jan 13 17:05:51 PST 2015"
在下面的方法中使用:
public static void currentSystemTime() {
Calendar calendar = new GregorianCalendar();
try {
System.out.println(format.parse(calendar.getTime().toString()));
} catch (ParseException ex) {
Logger.getLogger(DateDifference.class.getName()).log(Level.SEVERE, null, ex);
}
}
如何以匹配 SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
的文字格式获取系统时间?
最佳答案
您想将当前时间(Date
)格式化为String
但是DateFormat.parse(String)
恰恰相反。
使用DateFormat.format(Date)
为了你想要实现的目标:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println(sdf.format(new Date()));
注意:
构造函数new Date()
分配一个 Date
对象并对其进行初始化,使其代表分配时间,精确到毫秒。所以不需要使用 Calendar
来获取当前时间。
替代方案:
SimpleDateFormat
中有多个 format()
方法的重载,其中一个采用通用的 Object
参数:
这也接受格式化日期/时间作为 Long
是自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数。因此,以下内容也可以在不创建 Date
实例的情况下使用:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));
关于java - 通过SimpleDateFormat解析系统时间报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27924254/