通过SimpleDateFormat解析系统时间报错

Error when parsing system time through SimpleDateFormat

我想获取当前系统时间,然后通过格式化程序解析它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"); 匹配的文字格式的系统时间?

您想格式化当前时间(a Date) to String but 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来获取当前时间。

选择:

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

Format.format(Object)

这也接受格式表 date/time 作为 Long 自格林威治标准时间 00:00:00 1970 年 1 月 1 日以来的毫秒数。因此,以下内容也可以在不创建 Date 实例的情况下使用:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
System.out.println(sdf.format(System.currentTimeMillis()));

有错误,使用:

System.out.println(format.format(calendar.getTime()));