【问题标题】:Parse date from string to get milliseconds从字符串解析日期以获取毫秒
【发布时间】:2015-02-16 11:06:22
【问题描述】:

我正在尝试从包含日期的字符串中获取毫秒数,但似乎我得到了错误的值。这是我试图解析的字符串:2015-03-01 00:00:00, 我这样做是为了解析它:

 DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
 Date inputDate = dateFormat.parse(data.get(position).getValidTo());
 Log.d("--", inputDate.getDay() + " | " + inputDate.getMonth());

【问题讨论】:

  • 你从中得到了什么?
  • 你想要yyyy-MM-dd HH:mm:ss。然后不要Date上使用已弃用的方法......你只是在自找麻烦。
  • 请包含日志文件。并记录 data.get(position).getValidTo() 的内容以检查字符串是否有效
  • @MichałSzydłowski 当我做Log.d("--", inputDate.getDay() + " | " + inputDate.getMonth()); 我得到4 | 0
  • inputDate.getTime();它会以毫秒为单位给出时间。

标签: java android android-calendar android-date java-time


【解决方案1】:

使用 "MM" 而不是 "mm" 来获取月份。 (“mm”代表分钟)

inputDate.getTime() 将以毫秒为单位给出时间。

【讨论】:

    【解决方案2】:
     DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
     Date inputDate = dateFormat.parse("2014-10-12 12:00:00");
     System.out.println(inputDate.getTime());
    

    【讨论】:

      【解决方案3】:

      如果你添加依赖项,我会使用JodaTime 来做任何与日期相关的事情。

      import org.joda.time.DateTime;
      import org.joda.time.format.DateTimeFormat;
      import org.joda.time.format.DateTimeFormatter;
      

      并使用它

      String input = "2015-03-01 00:00:00";
      DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
      DateTime dt = DateTime.parse(input, formatter);
      
      System.out.println(dt.getDayOfWeek());
      System.out.println(dt.getMonthOfYear());
      

      【讨论】:

        猜你喜欢
        • 2020-03-30
        • 1970-01-01
        • 2018-12-22
        • 1970-01-01
        • 1970-01-01
        • 2020-08-27
        • 2012-03-04
        • 2014-12-17
        • 2015-07-24
        相关资源
        最近更新 更多