I have one date and time format as below:
Tue Apr 23 16:08:28 GMT+05:30 2013
I want to convert into milliseconds, but I actually dont know
In Kotlin,
Just use
timeInMilSeconds = date.time
where timeInMilSeconds
is milliseconds(var timeInMilSeconds: Long
) and date
is Date
Just to complement the given answers, if you need to convert the time given by the date to other time units you can use the TimeUnit API
Example:
TimeUnit.MILLISECONDS.toMinutes(millis)
I am providing the modern answer — though not more modern than it works on your Android API level too.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
"EEE MMM dd HH:mm:ss OOOO yyyy", Locale.ROOT);
String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
long timeInMilliseconds = OffsetDateTime.parse(givenDateString, formatter)
.toInstant()
.toEpochMilli();
System.out.println(timeInMilliseconds);
Output from this snippet is:
1366713508000
The SimpleDateFormat
, Date
and Calendar
classes used in most of the other answers are poorly designed and now long outdated. I recommend that instead you use java.time, the modern Java date and time API. Edit: The other answers were fine answers when the question was asked in 2013. Only time moves on, and we should not use SimpleDateFormat
, Date
and Calendar
any more.
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
org.threeten.bp
with subpackages.java.time
was first described.java.time
to Java 6 and 7 (ThreeTen for JSR-310).try this...
Calendar calendar = Calendar.getInstance();
calendar.set(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(),
timePicker.getCurrentHour(), timePicker.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();