1

我想获取当前系统时间,然后通过 formatter 解析它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");

4

2 回答 2

5

您想将当前时间 (a Date) 格式化为StringDateFormat.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用来获取当前时间。

选择:

format()中的方法有多个重载SimpleDateFormat,其中一个采用通用Object参数:

Format.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()));
于 2015-01-13T14:26:03.103 回答
1

有错误,使用:

System.out.println(format.format(calendar.getTime()));
于 2015-01-13T14:29:06.240 回答