Convert date and time to milliseconds in Android

喜夏-厌秋 提交于 2019-12-18 18:36:32

问题


I have Date and Time from DatePicker and TimePicker. Now i want to change the selected date and time into milliseconds. How can I do this???

For Example I have Date selected 2-5-2012 and Time is 20:43

Now I have to convert this Date Time into milliseconds something like

DateTimeInMilliseconds = 1234567890


回答1:


You can create a Calendar object with the values from your DatePicker and TimePicker:

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



回答2:


Merge the two strings together, and parse them using SimpleDateFormat.

Something like this:

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

Sample on IDEOne: http://ideone.com/nOJYQ4




回答3:


You can use this code

String string_date = "12-December-2012";

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



回答4:


The getTime() method of the Date class returns a long with the time in milliseconds.

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

So if you have a Date object somewhere like:

Date date;

You can do:

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

And it will print out the time in milliseconds.



来源:https://stackoverflow.com/questions/13223203/convert-date-and-time-to-milliseconds-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!