将日期字符串转换成Java中毫秒 [英] converting a date string into milliseconds in java

查看:383
本文介绍了将日期字符串转换成Java中毫秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
  计算在java中的日期/时间差

如何将未来的日期作为周六年02月17个2012年这样被转换为在Java毫秒,然后可以从当前时间中减去以毫秒为单位,得到剩余时间,直到该未来日期。

how would a future date such as Sat Feb 17 2012 be converted into milliseconds in java that can then be subtracted from the current time in milliseconds to yield time remaining until that future date.

推荐答案

最简单的方法是使用日期格式

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

一个比较难的技术(即基本上没有什么日期格式为你做)涉及自己解析它(这将考虑的最佳实践的):

A more difficult technique (that basically does what DateFormat does for you) involves parsing it yourself (this would not be considered best practice):

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

这篇关于将日期字符串转换成Java中毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆