【问题标题】:converting a date string into milliseconds in java [duplicate]在java中将日期字符串转换为毫秒[重复]
【发布时间】:2012-01-15 15:56:10
【问题描述】:

可能重复:
Calculate date/time difference in java

如何将未来的日期(例如 2012 年 2 月 17 日星期六)在 java 中转换为毫秒,然后可以从当前时间中减去以毫秒为单位的时间,以得出到该未来日期的剩余时间。

【问题讨论】:

  • 使用日期时间感知库(例如Joda Time))通常比转换为毫秒然后再转换回来要好:毫秒可能会在时区差异、没有 30 天的月份等方面丢失信息,闰年等。所以取决于所需的准确度......

标签: java android datetime


【解决方案1】:

最简单的技术是使用DateFormat:

String input = "Sat Feb 17 2012";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
long millisecondsFromNow = milliseconds - (new Date()).getTime();
Toast.makeText(this, "Milliseconds to future date="+millisecondsFromNow, Toast.LENGTH_SHORT).show();

一种更困难的技术(基本上是 DateFormat 为您所做的)涉及自己解析它(这被认为是最佳实践):

String input = "Sat Feb 17 2012";
String[] myDate = input.split("\\s+");
int year = Integer.parseInt(myDate[3]);
String monthString = myDate[1];
int mo = monthString.equals("Jan")? Calendar.JANUARY :
             monthString.equals("Feb")? Calendar.FEBRUARY :
             monthString.equals("Mar")? Calendar.MARCH :
             monthString.equals("Apr")? Calendar.APRIL :
             monthString.equals("May")? Calendar.MAY :
             monthString.equals("Jun")? Calendar.JUNE :
             monthString.equals("Jul")? Calendar.JULY :
             monthString.equals("Aug")? Calendar.AUGUST :
             monthString.equals("Sep")? Calendar.SEPTEMBER :
             monthString.equals("Oct")? Calendar.OCTOBER :
             monthString.equals("Nov")? Calendar.NOVEMBER :
             monthString.equals("Dec")? Calendar.DECEMBER : 0;
int day = Integer.parseInt(myDate[2]);
Calendar c = Calendar.getInstance();
c.set(year, mo, day);
long then = c.getTimeInMillis();
Time current_time = new Time();
current_time.setToNow();
long now = current_time.toMillis(false);
long future = then - now;
Date d = new Date(future);
//TODO use d as you need.
Toast.makeText(this, "Milliseconds to future date="+future, Toast.LENGTH_SHORT).show();

【讨论】:

  • 或者,您可以使用 SimpleDateFormat 在 2 行代码中完成。
  • @dusktreader,如果您要投反对票并提供新建议,您至少应该提供代码。我的回答经过深思熟虑,并提供了很多工作代码。这当然不值得投反对票,而且您的评论没有成效。
  • 这是我经常看到的糟糕编码实践的典型例子。此功能是在一个非常简单和干净的界面中提供的。自己动手是反生产的。我投了反对票,因为老实说,我觉得这是一个糟糕的答案,我什至评论告诉你为什么(我不需要这样做)。这是代码,尽管这是一个已经关闭了半年的死话题: DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy"); long millis = format.parse("2012 年 2 月 17 日星期六").getTime();
【解决方案2】:

首先,您必须解析您的字符串以获取其日期表示。 Here 是示例和一些文档。 然后你应该调用你的 Date 的 getTime() 方法。

【讨论】:

  • 链接失效了。
【解决方案3】:
DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
long futureTime = 0;
try {
    Date date = format.parse("Sat Feb 17 2012");
    futureTime = date.getTime();
} catch (ParseException e) {
    Log.e("log", e.getMessage(), e);
}

long curTime = System.currentTimeMillis();
long diff = futureTime - curTime;

【讨论】:

    【解决方案4】:

    在此代码的日期中传递未来日期的年、月和日,变量 diff 将给出到该日期的毫秒时间,

        Date date = new GregorianCalendar(year, month, day).getTime();
        Date today = new Date();
        long diff = date.getTime() - today.getTime();
    

    【讨论】:

      【解决方案5】:

      您可以简单地调用日期对象的 getTime() 方法。请按照下面的示例进行操作

      import java.util.Date;
      
      public class Test {
          @SuppressWarnings("deprecation")
          public static void main(String[] args) {
      
              System.out.println(new Date("Sat Feb 17 2012").getTime());
      
          }
      
      }
      

      【讨论】:

        【解决方案6】:
            try {  String str_date="11-June-07";
            SimpleDateFormat formatter ; 
            Date date ; 
            formatter = new SimpleDateFormat("dd-MMM-yy");
            date = (Date) formatter.parse(str_date);  
            Log.i("test",""+date);
            } catch (Exception e)
            {System.out.println("Exception :"+e);  }  
        
            Date d = new Date();
            long time = d.getTime();
            long timeDiff = time - lastTime;
        
        //timeDiff will contain your value.
        //import these two,
        //import java.text.SimpleDateFormat;
        //import java.util.Date;
        

        【讨论】:

          猜你喜欢
          • 2012-08-11
          • 2012-09-12
          • 2020-09-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-12-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多