I want to convert Long value to String or Date in this format dd/mm/YYYY.
I have this value in Long format: 1343805819061.
It is possible to convert it to Date format?
You can use below line of code to do this. Here timeInMilliSecond is long value.
String dateString = new SimpleDateFormat("MM/dd/yyyy").format(new Date(TimeinMilliSeccond));
Or you can use below code too also.
String longV = "1343805819061";
long millisecond = Long.parseLong(longV);
// or you already have long value of date, use this instead of milliseconds variable.
String dateString = DateFormat.format("MM/dd/yyyy", new Date(millisecond)).toString();
Reference:- DateFormat and SimpleDateFormat
P.S. Change date format according to your need.
You can use method setTime on the Date instance or the contructor Date(long);
setTime(long time)
Sets this Date object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
Date(long date)
Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT
Then use the simple date formater
see http://docs.oracle.com/javase/1.4.2/docs/api/javax/swing/text/DateFormatter.html
java.util.Date dateObj = new java.util.Date(timeStamp);
Here timeStamp is your long integer which is actually timestamp in millieseconds,
you get the java date object, now you can convert it into string by this
SimpleDateFormat dateformatYYYYMMDD = new SimpleDateFormat("yyyyMMdd");
SimpleDateFormat dateformatMMDDYYYY = new SimpleDateFormat("MMddyyyy");
StringBuilder nowYYYYMMDD = new StringBuilder( dateformatYYYYMMDD.format( dateObj ) );
StringBuilder nowMMDDYYYY = new StringBuilder( dateformatMMDDYYYY.format( dateObj ) );
java.time and ThreeTenABP
I am providing the modern answer. I suggest using java.time, the modern Java date and time API, for your date work. This will work on your Android version:
// Take Catalan locale as an example for the demonstration
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("ca"));
long millisecondsSinceEpoch = 1_343_805_819_061L;
ZonedDateTime dateTime = Instant.ofEpochMilli(millisecondsSinceEpoch)
.atZone(ZoneId.systemDefault());
String dateString = dateTime.format(dateFormatter);
System.out.println("As formatted date: " + dateString);
Output is:
As formatted date: 01/08/2012
I recommend that you use a built-in localized date format for presentation to your user. I took Catalan date format just as an example. Formats for many languages, countries and dialects are built-in.
The SimpleDateFormat class used in most of the old answers is a notorious troublemaker of a class. The Date class also used is poorly designed too. Fortunately they are both long outdated. It’s no longer recommended to use any of those. And I just find java.time so much nicer to work with.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
if thre is 10 digits in long then try this
long DateInLong= 1584212400;
Date date = new Date(DateInLong*1000L);
SimpleDateFormat simpledateformate= new SimpleDateFormat("yyyy-MM-dd");
String DATE = simpledateformate.format(date);
public String getDuration(long msec) {
if (msec == 0)
return "00:00";
long sec = msec / 1000;
long min = sec / 60;
sec = sec % 60;
String minstr = min + "";
String secstr = sec + "";
if (min < 10)
minstr = "0" + min;
if (sec < 10)
secstr = "0" + sec;
return minstr + ":" + secstr;
}
Related
getting wrong results after converting 12hrs time format to utc.
String inputPa = "hh:mm a";
String OutPa = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat inputPatter = new SimpleDateFormat(inputPa);
SimpleDateFormat outputPatter = new SimpleDateFormat(OutPa);
Date date1 = null;
String str1 = null;
try {
date1 = inputPatter.parse(txtStartTime.getText().toString());
str1 = outputPatter.format(date1);
Log.d("mycheck", str1);
} catch (ParseException e) {
e.printStackTrace();
}
java.time and ThreeTenABP
I assumed you wanted today’s date in your time zone.
String inputPa = "hh:mm a";
DateTimeFormatter timeFormatter12Hours = DateTimeFormatter.ofPattern(inputPa, Locale.ENGLISH);
ZoneId zone = ZoneId.of("America/Detroit");
String timeString = "11:34 AM";
LocalTime time = LocalTime.parse(timeString, timeFormatter12Hours);
Instant inst = LocalDate.now(zone).atTime(time).atZone(zone).toInstant();
System.out.println(inst);
Output from this example is:
2020-05-30T15:34:00Z
I would not bother converting the Instant to a string explicitly. It prints in UTC in your desired format when you print it, thus implicitly invoking its toString method (the format is ISO 8601, the international standard).
Please fill in your desired time zone. To rely on the device’ time zone setting set zone to ZoneId.systemDefault().
I am of course happy to use java.time, the modern Java date and time API. You can do that on your Android version too, see the details below.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
public tring getCurrentUTC(Date time) {
SimpleDateFormat outputFmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
outputFmt.setTimeZone(TimeZone.getTimeZone("UTC"));
return outputFmt.format(time);
}
You can use this code to get current UTC time.
For you question, you just need convert the time string to the Date format.
I am getting date time from rest api as like this "2020-02-13T16:57:13.04 . How can i convert in java for android? So that i can use only date or time separately?
I have tried by this way
String dateStr = rowsArrayList.get(position).getDisplayDate();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = null;
try {
date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
Log.d("testDate",formattedDate);
} catch (ParseException e) {
e.printStackTrace();
Log.d("testDate",e.toString());
}
But getting the error
java.text.ParseException: Unparseable date: "2020-02-13T16:57:13.04"
Use yyyy-MM-dd'T'HH:mm:ss.SS as format instead of yyyy-MM-dd'T'HH:mm:ss'Z'
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS", Locale.ENGLISH);
java.time
You can also achieve this with java.time, the modern Java date and time API because the old classes (Date, Calendar and SimpleDateFormat) have lots of problems and design issues:
String sourceDateTime = "2020-02-13T16:57:13.04";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SS").withZone(DateTimeZone.UTC);
LocalDateTime localDateTime = LocalDateTime.parse(sourceDateTime, dateTimeFormatter);
LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();
System.out.println(localDate.toString() + " -> " + localTime.toString());
//Output should be: 2020-02-13 -> 16:57:13.040
Question: Can I use java.time on Android?
From Android 8.0 (API level 26) the modern API comes built-in.
For older android version, you can use ThreeTenABP, Android edition of ThreeTen Backport
SimpleDateFormat cannot parse your date-time string correctly.
SimpleDateFormat is notoriously troublesome and long outdated. Neither for this nor for any other purpose should you use it. Instead just use the LocalDateTime class from java.time, the modern Java date and time API. It parses your string wothout any explicit formatter.
You can’t with SimpleDateFormat
Your string has two decimals on the second of minute, .04, signifying 4 hundredths of a second. SimpleDateFormat only supports exactly three decimals on the seconds, not two or four or any other number. So there is no way that it can parse your string correctly.
java.time
It seems that you are assuming that the string you parse is in UTC and you want to convert it to the default time zone of your device. Your string is in ISO 8601 format, the format that the classes of java.time parse as their default, so we don’t need to specify any formatter.
String dateStr = "2020-02-13T16:57:13.04";
LocalDateTime dateTime = LocalDateTime.parse(dateStr);
ZonedDateTime inDefaultTimeZone = dateTime.atOffset(ZoneOffset.UTC)
.atZoneSameInstant(ZoneId.systemDefault());
System.out.println(inDefaultTimeZone);
On my computer in Europe/Copenhagen time zone the output from this snippet is:
2020-02-13T17:57:13.040+01:00[Europe/Copenhagen]
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
Wikipedia article: ISO 8601
Take out the 'Z' on your format string
This should work:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.ENGLISH);
Or if you want to keep the milliseconds then use SS:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SS", Locale.ENGLISH);
String dateStr = "Jul 16, 2013 12:08:59 AM";
SimpleDateFormat df = new SimpleDateFormat("MMM dd, yyyy HH:mm:ss a", Locale.ENGLISH);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = df.parse(dateStr);
df.setTimeZone(TimeZone.getDefault());
String formattedDate = df.format(date);
im trying to convert a string(with unix timestamp) to an date with the format ( dd-MM-yyyy)
and this is working partly. The problem im having now is that my date is in 17-01-1970 (instead of march 16 2015)
im converting it like this:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = null;
int dateMulti = Integer.parseInt(Date);
Calendar cal = Calendar.getInstance(Locale.ENGLISH);
cal.setTimeInMillis(dateMulti);
String date = DateFormat.format("dd-MM-yyyy", cal).toString();
Log.d("test",date);
try {
d = dateFormat.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
where Date = 1427101853
and the result = 17-01-1970
what am i doing wrong?
You are using the wrong format string in the first line:
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy");
mm is minutes. Use MM (months) instead.
edit A Unix timestamp is a number of seconds since 01-01-1970 00:00:00 GMT. Java measures time in milliseconds since 01-01-1970 00:00:00 GMT. You need to multiply the Unix timestamp by 1000:
cal.setTimeInMillis(dateMulti * 1000L);
Why you have "dd-mm-yyyy" in SimpleDateFormat and "dd-MM-yyyy" in DateFormat.format? Use this :
String date = DateFormat.format("dd-mm-yyyy", cal).toString();
If you want minutes, if you want months you have to put MM like #Jesper said :)
I should like to contribute the modern answer.
java.time
DateTimeFormatter dateFormatter = DateTimeFormatter
.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.forLanguageTag("da"));
String unixTimeStampString = "1427101853";
int dateMulti = Integer.parseInt(unixTimeStampString);
ZonedDateTime dateTime = Instant.ofEpochSecond(dateMulti)
.atZone(ZoneId.of("Africa/Conakry"));
String formattedDate = dateTime.format(dateFormatter);
System.out.println(formattedDate);
The output from this snippet is:
23-03-2015
The output agrees with an online converter (link at the bottom). It tells me your timestamp equals “03/23/2015 # 9:10am (UTC)” (it also agrees with the date you asked the question). Please substitute your time zone if it didn’t happen to be Africa/Conakry.
The date-time classes that you were using — SimpleDateFormat, Date and Calendar — are long outdated and poorly designed, so I suggest you skip them and use java.time, the modern Java date and time API, instead. A minor one among the many advantages is it accepts seconds since the epoch directly, so you don’t need to convert to milliseconds. While this was no big deal, doing your own time conversions is a bad habit, you get clearer, more convincing and less error-prone code from leaving the conversions to the appropriate library methods.
Question: Can I use java.time on Android?
Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26, I’m told) the modern API comes built-in.
In Java 6 and 7 get the ThreeTen Backport, the backport of the new classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
I wrote and ran the above snippet using the backport to make sure it would be compatible with ThreeTenABP.
Links
Timestamp Converter
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.
I was also facing the same issue when I was using SimpleDateFormat Here is a method I have made, which is working fine for me.
private String getmDate(long time1) {
java.util.Date time = new java.util.Date((long) time1 * 1000);
String date = DateFormat.format("dd-MMM-yyyy' at 'HH:mm a", time).toString();
return date + "";
}
you can change the date format as you desire.
I want to convert my date (which is in String format), e.g. 13-09-2011, into Timestamp. I used below code but I got the 2011-09-13 00:00:00.0
as a result. But I want Timestamp like,1312828200000 format.
I cannot understand how to convert that.
My code:
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " +timeStampDate);
If you use getTime() of Date object you will get time in millisecond.
No need to use Timestamp to get your result.
String str_date="13-09-2011";
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = (Date)formatter.parse(str_date);
System.out.println("Today is " +date.getTime());
The above code will print something like 1312828200000 you need and this is long value.
String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date);
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;
This line:
"Today is " +timeStampDate
calls TimeStamp.toString() method "which Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds."
The TimeStamp you got internally has the value you want. If you want to get it than use:
System.out.println("Today is " + timeStampDate.getTime());
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
java.sql.Timestamp timeStampDate = new Timestamp(date.getTime());
System.out.println("Today is " + timeStampDate.getTime());
Or if you don't need the Timestamp, you can directly use date.getTime(). It "Returns the Date as a millisecond value.":
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
System.out.println("Today is " + date.getTime());
tl;dr
Use modern java.time classes.
LocalDate.parse(
"13-09-2011" ,
DateTimeFormatter.ofPattern( "dd-MM-uuuu" )
)
.atStartOfDay(
ZoneId.of( "Africa/Casablanca" ) // Or use `ZoneOffset.UTC` instead of a zone.
)
.toInstant()
.toEpochMilli()
See this code run live at IdeOne.com.
1315872000000
Details
Apparently you want to represent the first moment of a particular date as a count of milliseconds since the epoch reference of first moment of 1970 in UTC.
java.time
The modern approach uses the java.time classes that years ago supplanted the troublesome legacy classes such as Date, Calendar, and SimpleDateFormat.
First parse your input string as a LocalDate, for a date-only value without time-of-day and without time zone.
Tip: Rather then using such custom formats when exchanging date-time values as text, use standard ISO 8601 formats. The java.time classes use them by default when parsing/generating strings.
String input = "13-09-2011" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MM-uuuu" ) ;
LocalDate ld = LocalDate.parse( input , f ) ;
Determine the first moment of the day on that date. Doing so requires a time zone. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "America/Montreal" ) ;
Never assume the day starts at 00:00. In some zones on some dates, the day may start at another time such as 01:00. Let java.time determine first moment.
ZonedDateTime zdt = ld.startOfDay( z ) ; // Determine first moment of the day on this date in this zone. May not be 00:00.
Adjust to UTC from that zone by extracting a Instant.
Instant instant = zdt.toInstant() ;
Get a count of milliseconds since 1970-01-01T00:00Z. Beware of possible data loss, as an Instant carries a finer resolution of nanoseconds. Any microseconds or nanoseconds will be ignored.
long millisecondsSinceEpoch = instant.toEpochMilli() ;
You can go back the other direction, from a count-from-epoch to a Instant.
Instant instant = Instant.ofEpochMilli( millisecondsSinceEpoch) ;
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
Kotlin
val dateString = "17-09-2021"
val formatter = SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH)
val date = formatter.parse(dateString) as Date
Log.i("i","Today is " + date.time)
You'll get something that resembles 1616668471659
It may can help you
long time= System.currentTimeMillis();//timestamp in milliseconds of current time
String tp = Long.toString(time);//use timestamp as a string
I have been digging into the question for a while in StackOverflow
Android get Current UTC time
and
How can I get the current date and time in UTC or GMT in Java?
I have tried two ways to get the current time of my phone in GMT. I am in Spain and the difference is GMT+2. So let's see with an example:
1º attemp: I created a format and applied it to System.currentTimeMillis();
DateFormat dfgmt = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String gmtTime = dfgmt.format(new Date());
//Using System.currentTimeMillis() is the same as new Date()
Date dPhoneTime = dfgmt.parse(gmtTime);
Long phoneTimeUTC = dPhoneTime.getTime();
I need to substract that time to another time, that's why i do the cast to Long.
DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date arrivalDate = df.parse(item.getArrivalDate());
//the String comes from JSON and is for example:"UTC_arrival":"2011-05-16 18:00:00"
//which already is in UTC format. So the DateFormat doesnt have the GMT paramater as dfgmt
diff = arrival.getTime() - phoneTimeUTC ;
I also tried this:
Calendar aGMTCalendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()
And still I dont get the right difference. But if I do this:
Long phoneTimeUTC = aGMTCalendar.getTimeInMillis()-3600000*2;
It does work OK.
Any ideas?
Thanks a lot,
David.
This works for sure!
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("dd:MM:yyyy HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(dateFormatGmt.format(new Date())+"");
Specify the format, and you will get it in GMT!
As far as I read the calendar.getTimeInMillis(); returns the UTC time in millis. I used the following code and compared it to the Epoch in this site http://www.xav.com/time.cgi.
public int GetUnixTime()
{
Calendar calendar = Calendar.getInstance();
long now = calendar.getTimeInMillis();
int utc = (int)(now / 1000);
return (utc);
}
Giora
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
Date currentLocalTime = cal.getTime();
DateFormat date = new SimpleDateFormat("dd-MM-yyy HH:mm:ss z");
date.setTimeZone(TimeZone.getTimeZone("GMT"));
String localTime = date.format(currentLocalTime);
System.out.println(localTime);
Have a look and see if that works.
you can always use:
Calendar mCalendar = Calendar.getInstance(TimeZone.getTimeZone("gmt"));
long millies = mCalendar.getTimeInMillis();
or
Calendar mCalendar = Calendar.getInstance(TimeZone.getTimeZone("utc"));
long millies = mCalendar.getTimeInMillis();
Output: 2016-08-01 14:37:48 UTC
final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z");
dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Works fine.
java.time and ThreeTenABP
I am providing the modern answer.
To get the difference in milliseconds between the phone time now — in Spain or any other place — and a certain time in the past:
// Example arrival time for the demonstration
Instant arrival = Instant.parse("2020-02-29T12:34:56.789Z");
Instant currentTime = Instant.now();
long difference = ChronoUnit.MILLIS.between(arrival, currentTime);
System.out.println("Difference is " + difference + " milliseconds");
Example output:
Difference is 2610350731 milliseconds
If you want the difference in seconds or some other time unit, just use the appropriate enum constant from the ChronoUnit enum instead of ChronoUnit.MILLIS.
There is no need to worry about the device time zone, nor about formatting or parsing the time, those worries only lead to over-complication of this basically simple matter.
BTW the epoch is one well-defined point in time, it doesn’t vary with time zone, it’s the same all over the world. Therefore the count of milliseconds from the epoch till now is also the same in all time zones. Some say that this count is always in UTC because the epoch is (usually) defined in UTC, as January 1, 1970 at 00:00 UTC.
Question: Doesn’t java.time require Android API level 26?
java.time works nicely on both older and newer Android devices. It just requires at least Java 6.
In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.