Android convert date and time to milliseconds
Update for DateTimeFormatter introduced in API 26.
Code can be written as below for API 26 and above
// Below Imports are required for this code snippet
// import java.util.Locale;
// import java.time.LocalDateTime;
// import java.time.ZoneOffset;
// import java.time.format.DateTimeFormatter;
String date = "Tue Apr 23 16:08:28 GMT+05:30 2013";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
LocalDateTime localDate = LocalDateTime.parse(date, formatter);
long timeInMilliseconds = localDate.atOffset(ZoneOffset.UTC).toInstant().toEpochMilli();
Log.d(TAG, "Date in milli :: FOR API >= 26 >>> " + timeInMilliseconds);
// Output is -> Date in milli :: FOR API >= 26 >>> 1366733308000
But as of now only 6% of devices are running on 26 or above. So you will require backward compatibility for above classes. JakeWharton has been written ThreeTenABP which is based on ThreeTenBP, but specially developed to work on Android. Read more about How and Why ThreeTenABP should be used instead-of java.time, ThreeTen-Backport, or even Joda-Time
So using ThreeTenABP, above code can be written as (and verified on API 16 to API 29)
// Below Imports are required for this code snippet
// import java.util.Locale;
// import org.threeten.bp.OffsetDateTime;
// import org.threeten.bp.format.DateTimeFormatter;
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("Date in milli :: USING ThreeTenABP >>> " + timeInMilliseconds);
// Output is -> Date in milli :: USING ThreeTenABP >>> 1366713508000
Ole covered summarised information (for Java too) in his answer, you should look into.
Below is old approach (and previous version of this answer) which
should not be used now
Use below method
String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
Date mDate = sdf.parse(givenDateString);
long timeInMilliseconds = mDate.getTime();
System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
Read more about date and time pattern strings.
android convert date string to time in milliseconds
Use MM for month.
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
and to get Time use Date.getTime() method.
for more information take a look at Date and Time Patterns
Android converting the time in milliseconds
To understand what's happening:
Calendar.getInstance()
creates aCalendar
with the current date/time in the JVM default timezone- You set the hour, minutes and seconds (to
01:30:00
I suppose) - You call
getTimeInMillis()
, that returns the number of milliseconds since unix epoch (1970-01-01T00:00Z
)
Then you use this milliseconds value with TimeUnit
, but that's not what you need. TimeUnit
will treat the number of milliseconds as an amount of time, but what you need is a time of the day:
- a time of the day is a specific moment in a day, such as "10 AM" or "05:30 PM".
- an amount of time is just, well, an amount of elapsed time, such as "10 minutes and 45 seconds", or "2 years, 4 months, 5 days and 17 hours", but it's not attached to a specific point in time ("10 minutes relative to what?"); it's just the amount of time, by itself.
Although both concepts might use the same words ("hours", "minutes", "seconds", etc), they're not the same thing.
TimeUnit
deals with amounts of time, so it does conversions like "1000 seconds is equivalent to how many minutes?".
Example: TimeUnit.MILLISECONDS.toHours(value)
returns the number of hours equivalent to value
milliseconds (not the time of the day). As the value you're using is the result of getTimeInMillis()
, you're getting the total number of hours since January 1970.
By using the result of getTimeInMillis()
(which represents a specific point in time) with TimeUnit
, you're misusing the value, treating like it was an amount of time.
To format a date, you can use a SimpleDateFormat
:
Calendar mycalendar = Calendar.getInstance();
mycalendar.set(Calendar.HOUR_OF_DAY, 1);
mycalendar.set(Calendar.MINUTE, 30);
mycalendar.set(Calendar.SECOND, 0);
// format: hour:minute:second
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
String hms = sdf.format(mycalendar.getTime()); // 01:30:00
With this, hms
will have the value 01:30:00
. Check the javadoc to know what the format HH:mm:ss
means, so you can change it in case you need a different format (If you want just 01:30
, for example, the format will be HH:mm
).
Java new Date/Time API
The old classes (Date
, Calendar
and SimpleDateFormat
) have lots of problems and design issues, and they're being replaced by the new APIs.
In Android you can use the ThreeTen Backport, a great backport for Java 8's new date/time classes. To make it work, you'll also need the ThreeTenABP (more on how to use it here).
First you create a org.threeten.bp.LocalTime
(a class that represents a time of the day), then you format it with a org.threeten.bp.format.DateTimeFormatter
:
// create time for 01:30
LocalTime time = LocalTime.of(1, 30);
// format: hour:minute:second
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("HH:mm:ss");
String hms = fmt.format(time);
System.out.println(hms); // 01:30:00
Also, check the javadoc for all available formats.
Android: Convert date to milliseconds
The simplest way is to convert Date
type to milliseconds:
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy, HH:mm");
formatter.setLenient(false);
Date curDate = new Date();
long curMillis = curDate.getTime();
String curTime = formatter.format(curDate);
String oldTime = "05.01.2011, 12:45";
Date oldDate = formatter.parse(oldTime);
long oldMillis = oldDate.getTime();
Convert date and time to milliseconds in Android
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();
How to get time in milliseconds from a string in android?
Try to use this:
try {
String string = "Mon, 10 Mar 2017 03:26:00 p.m.";
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, Integer.parseInt(string.substring(17, 19)));
calendar.set(Calendar.MINUTE, Integer.parseInt(string.substring(20, 22)));
calendar.set(Calendar.AM_PM, string.contains("a.m.") ? 0 : 1);
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Toast.makeText(getApplicationContext(), "cal: " + dateFormat.format(calendar.getTime())+ " , milli sec: "+calendar.getTimeInMillis(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "exe: " + e, Toast.LENGTH_LONG).show();
}
How to convert time stamp to get exact milliseconds difference in Android?
The date-time API of java.util
and their formatting API, SimpleDateFormat
are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
- For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
- If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Using the modern date-time API:
import java.time.Duration;
import java.time.LocalTime;
public class Main {
public static void main(String[] args) {
long millisBetween = Duration.between(LocalTime.parse("05:41:54.771"), LocalTime.parse("05:42:03.465"))
.toMillis();
System.out.println(millisBetween);
}
}
Output:
8694
Learn more about the modern date-time API from Trail: Date Time.
Using the legacy API:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
DateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS", Locale.ENGLISH);
long millisBetween = sdf.parse("05:42:03.465").getTime() - sdf.parse("05:41:54.771").getTime();
System.out.println(millisBetween);
}
}
Output:
8694
Some important notes about this solution:
- Without a date,
SimpleDateFormat
parses the time string with a date ofJanuary 1, 1970 GMT
. Date#getTime
returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by thisDate
object.- Use
H
instead ofh
for a time value in24-Hour
format.
Convert date time with AM and PM to milisecound?
You should use SimpleDateformat.
String dateString = "5/4/2014 4:39:52 PM";
SimpleDateFormat format =
new SimpleDateFormat("dd/MM/yyyy hh:mm:ss a");
Date date = format.parse(dateString);
long millisecond = date.getTime();
This class is used to parse strings into dates in java.
How to convert a date to milliseconds
You don't have a Date
, you have a String
representation of a date. You should convert the String
into a Date
and then obtain the milliseconds. To convert a String
into a Date
and vice versa you should use SimpleDateFormat
class.
Here's an example of what you want/need to do (assuming time zone is not involved here):
String myDate = "2014/10/29 18:10:45";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millis = date.getTime();
Still, be careful because in Java the milliseconds obtained are the milliseconds between the desired epoch and 1970-01-01 00:00:00.
Using the new Date/Time API available since Java 8:
String myDate = "2014/10/29 18:10:45";
LocalDateTime localDateTime = LocalDateTime.parse(myDate,
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss") );
/*
With this new Date/Time API, when using a date, you need to
specify the Zone where the date/time will be used. For your case,
seems that you want/need to use the default zone of your system.
Check which zone you need to use for specific behaviour e.g.
CET or America/Lima
*/
long millis = localDateTime
.atZone(ZoneId.systemDefault())
.toInstant().toEpochMilli();
Related Topics
Kotlin and Firebase Read and Write Data
Applying Word Stemming in Searchview for Fetch Data from Firebase Database
Google Play App Description Formatting
What Are the Android Sdk Build-Tools, Platform-Tools and Tools? and Which Version Should Be Used
Allow Multi-Line in Edittext View in Android
How to Make Edittext Not Editable Through Xml in Android
How to Record Video from Background of Application:Android
Android Screen Size Hdpi, Ldpi, Mdpi
Gridview VS Gridlayout in Android Apps
How to Change Screen Orientation in the Android Emulator
What Is Meant by Ems? (Android Textview)
How to Connect with Remote Debugger
How to Modify Ripple Color When Using Attr/Selectableitembackground as Background
Android Device Does Not Show Up in Adb List
How to Use the Proguard in Android Studio
How to Use Data-Binding with Fragment
Circular Dependencies Cannot Exist in Relativelayout, Android