<分区>
Possible Duplicate:
Calculate date/time difference in java
如何将 future 日期(例如 Sat Feb 17 2012)转换为 Java 中的毫秒数,然后可以从当前时间(以毫秒为单位)中减去该日期以得出该 future 日期之前的剩余时间。
<分区>
Possible Duplicate:
Calculate date/time difference in java
如何将 future 日期(例如 Sat Feb 17 2012)转换为 Java 中的毫秒数,然后可以从当前时间(以毫秒为单位)中减去该日期以得出该 future 日期之前的剩余时间。
最佳答案
最简单的技术是使用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();
关于java - 在java中将日期字符串转换为毫秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8427169/