【问题标题】:Java. Get date and time from string with milliseconds [duplicate]爪哇。以毫秒为单位从字符串中获取日期和时间[重复]
【发布时间】:2014-07-08 06:18:43
【问题描述】:

我尝试以毫秒为单位从字符串中获取日期和时间:

 SimpleDateFormat formatDate = new SimpleDateFormat("dd.MM.yyyy HH:mm");
 Date modifDate = new Date(Long.parseLong(ftpClient.getModificationTime(file_directory)));
 System.out.println(formatDate.format(modifDate));

但我在第二行有一个例外:java.lang.NumberFormatException: For input string: "213 20140601042221。我的错误在哪里,我该如何解决?

非常感谢!

【问题讨论】:

  • 你如何期待"213 20140601042221 被解析为一个long?
  • 我猜你的String 不是Long。如果您的String 是213 20140601042221,则应拆分为2 个Longs。
  • 这有可能回答您的问题吗? parsing a date string from FTPClient.getModificationTime()
  • 21320140601042221 是您想要的值或可能只是20140601042221 在Long.parseLong 中使用split(" ")[1]

标签: java date time


【解决方案1】:

FTPClient.getModificationTime()

它以YYYYMMDDhhmmss 格式返回代表最后文件修改时间的String。因此,如果您尝试将其解析为Long,则不要使用该值。

你可以这样做。

try {
    SimpleDateFormat sd=new SimpleDateFormat("YYYYMMDDhhmmss");//From FTPClient
    Date date=sd.parse("20140601042221");//Parse String to date
    SimpleDateFormat sd2=new SimpleDateFormat("dd.MM.yyyy HH:mm");
    System.out.println(sd2.format(date));
} catch (ParseException e) {
    e.printStackTrace();
}

【讨论】:

  • 任务,非常感谢!
【解决方案2】:

我不确定213 是什么,但20140601042221 似乎是

YYYYmmddHHMMssSSS

这与你所说的不符

new SimpleDateFormat("dd.MM.yyyy HH:mm");

见http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

提示:使用parse 方法

【讨论】:

    【解决方案3】:

    试试这个代码:

        String dateString=ftpClient.getModificationTime(file_directory));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        Date modificationDate = 
            dateFormat.parse(dateString.substring(dateString.indexOf(" ") + 1));
        SimpleDateFormat dateOutputFormat=new SimpleDateFormat("dd.MM.yyyy HH:mm");
        System.out.println(""+dateOutputFormat.format(modificationDate));
    

    【讨论】:

    • 这个日期格式错误
    • @ScaryWombat 我在 java SE 应用程序上测试了这个模式,它给出了输出。 “08.07.2014 12:06:02:658”
    • 20140601042221 不是08.07.2014
    • 你说的是“yyyyddMMHHmmssSS”吗?这给出了 20140807121235401 作为输出@ScaryWombat
    • 20140601042221 不是毫秒,所以new Date(... 是错误的。应该使用parse方法
    【解决方案4】:

    尝试摆脱 213 并执行以下操作:

    SimpleDateFormat formatDate = new SimpleDateFormat("YYYYmmddHHMMssSSS"); System.out.println(formatDate.format(ftpClient.getModificationTime(file_directory)));

    【讨论】:

    • 我想你的意思是parse
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 1970-01-01
    • 2014-10-16
    • 2011-05-31
    相关资源
    最近更新 更多