java - 通过SimpleDateFormat解析系统时间报错

标签 java date simpledateformat string-formatting systemtime

我想获取当前系统时间,然后通过格式化程序解析它 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 参数:

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()));

关于java - 通过SimpleDateFormat解析系统时间报错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27924254/

相关文章:

java - 在不同的应用程序中写入和读取 Cookie

mysql下一个字段的日期

java - 使用 SimpleDateFormat 将字符串转换为日期

Java SimpleDateFormat 错误?

java - SimpleDateFormat.parse 方法不解析所选时区

java - 使用 Spring Security 加载用户 session

java - 嵌套类型参数如何工作?

java - 短暂 hibernate 直到点击功能

Java字符串到不同格式的日期转换

r - 查找每组中的最低日期