在Android中将日期和时间转换为毫秒

时间:2012-11-04 21:39:49

标签: android datepicker datetimepicker timepicker

DatePicker TimePicker 日期时间。现在我想将选定的日期和时间更改为毫秒。我怎么能这样做?

例如,我选择日期 2-5-2012 时间 20:43

现在我必须将此日期时间转换为毫秒,例如

DateTimeInMilliseconds = 1234567890

4 个答案:

答案 0 :(得分:49)

您可以使用DatePicker和TimePicker中的值创建一个Calendar对象:

Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), 
             timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();

答案 1 :(得分:11)

将两个字符串合并在一起,并使用SimpleDateFormat解析它们。

这样的事情:

String toParse = myDate + " " + myTime; // Results in "2-5-2012 20:43"
SimpleDateFormat formatter = new SimpleDateFormat("d-M-yyyy hh:mm"); // I assume d-M, you may refer to M-d for month-day instead.
Date date = formatter.parse(toParse); // You will need try/catch around this
long millis = date.getTime();

IDEOne上的示例:http://ideone.com/nOJYQ4

答案 2 :(得分:6)

您可以使用此代码

String string_date = "12-December-2012";

SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date d = f.parse(string_date);
long milliseconds = d.getTime();

答案 3 :(得分:4)

getTime()类的Date方法返回long时间,以毫秒为单位。

http://developer.android.com/reference/java/util/Date.html

所以如果你有一个Date对象,比如:

Date date;

你可以这样做:

System.out.println(date.getTime());

它将以毫秒为单位打印出时间。

相关问题