Get day name from full calender date format - android

How to get name day name like (Wednesday - Thursday) from this date format "Wed Jan 30 00:00:00 GMT+02:00 2019"

java.time
It seems that what you’ve got is an instance of the java.util.Date class. That’s a poorly designed class that is long outdated, so first thing is to see if you can avoid that and have an instance of a class from java.time, the modern Java date and time API, instead.
However, if you got the Date from a legacy API that you cannot change or don’t want to change just now, first thing is to convert it to a modern Instant and then perform further conversions from there. The following snippet uses ThreeTenABP, more on that below.
Date yourOldfashionedDate = getFromLegacyApi();
Instant modernInstant = DateTimeUtils.toInstant(yourOldfashionedDate);
String dayName = modernInstant.atZone(ZoneId.systemDefault())
.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
System.out.println("Day name is " + dayName);
Output given the date from your question:
Day name is Wednesday
If what you got was a String (probably a string returned from Date.toString at some point), you need to parse it first:
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
String dateString = "Wed Jan 30 00:00:00 GMT+02:00 2019";
ZonedDateTime dateTime = ZonedDateTime.parse(dateString, dateFormatter);
String dayName = dateTime.getDayOfWeek()
.getDisplayName(TextStyle.FULL, Locale.ENGLISH);
You see that the last bit is exactly like before.
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) the modern API comes built-in. Only in this case use yourOldfashionedDate.toInstant() instead of DateTimeUtils.toInstant(yourOldfashionedDate).
In 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.

You can use SimpleDateFormat for it and the format part that gives you the full day name is EEEE.
Hope it helps!

You will need to first parse your String into a Calendar object using a SimpleDateFormat :
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
try {
cal.setTime(sdf.parse("Wed Jan 30 00:00:00 GMT+02:00 2019"));
} catch (ParseException e) {
// Log invalid date format
}
Then extract the day from your Calendar object:
String day = cal.getDisplayName(Calendar.DAY_OF_WEEK,Calendar.LONG,Locale.ENGLISH);

## Here, I have attached a method that will give you expected output ##
public void dayName(){
String weekDay,time;
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE MMM dd HH:mm", Locale.US);
SimpleDateFormat dayFormat1 = new SimpleDateFormat("hh:mm yyyy", Locale.US);
dayFormat.setTimeZone(TimeZone.getTimeZone("ITC"));
dayFormat1.setTimeZone(TimeZone.getTimeZone("GMT"));
Calendar calendar = Calendar.getInstance();
weekDay = dayFormat.format(calendar.getTime());
time=dayFormat1.format(calendar.getTime());
Log.e(TAG, "dayName: "+weekDay+" GMT+"+time );// out put looks like : Tuesday Jan 29 17:58 GMT+05:58 2019
}
I have used two TimeZone are ITC and GMT

Related

how to format date string from input could be of multiple string formats

Having input date string could be possible as
"2020-01-25T21:59:27Z"
or
"Sat Jan 25 20:06:07 +0000 2020"
or a Long
and expect one to display is like
Jan 25, 2020
how to get the desired formatted date string?
update:
#Ole V.V provided a very good suggestion, it's just cannt apply it with android lib case.
but I guess there is no single format for all these three cases, so have to try out one by one. such as for the ISO8601 one to do something like:
return try {
val dateStr = "Sat Jan 25 20:06:07 +0000 2020". //ISO8601
val format = SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.getDefault())
val dsipFormat = SimpleDateFormat("MMM dd yyyy", Locale.getDefault()) // for display result
val date = format.parse(dateStr) // parse it to date
dsipFormat.format(date) // returning the display result
} catch (e: Exception) {
Log.e("+++", "+++ error: $e")
""
}
If there is better approach?
java.time and ThreeTenABP
My solution is to build three formatters for the three possible input formats and then for each input try the formatters in turn. For a simple demomstration of the idea:
DateTimeFormatter[] inputFormatters = {
DateTimeFormatter.ISO_INSTANT,
DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss xx yyyy", Locale.ROOT),
new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.toFormatter()
};
DateTimeFormatter displayFormatter
= DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.US);
for (String inputString : new String[] {
"2020-01-25T21:59:27Z",
"Sat Jan 25 20:06:07 +0000 2020",
"1566777888999"
}) {
// try the formatters in turn and see which one works
for (DateTimeFormatter formatter : inputFormatters) {
try {
ZonedDateTime dateTime = formatter.parse(inputString, Instant.FROM)
.atZone(ZoneId.systemDefault());
System.out.format("%-30s was parsed to %s%n",
inputString, dateTime.format(displayFormatter));
break;
} catch (DateTimeParseException ignore) {
// Ignore, try next format
}
}
}
In my time zone (Europe/Copenhagen) output from this snippet is:
2020-01-25T21:59:27Z was parsed to Jan 25, 2020
Sat Jan 25 20:06:07 +0000 2020 was parsed to Jan 25, 2020
1566777888999 was parsed to Aug 26, 2019
Since it is never the same date in all time zones, output will vary with time zone.
I am recommending java.time, the modern Java date and time API. I saw that you tagged the question simpledateformat, but the SimpleDateFormat class is notoriously troublesome and long outdated, so I recommend against using it. And I am exploiting the fact that your first format is standard ISO 8601 and that java.time has a built-in formatter for it, DateTimeFormatter.ISO_INSTANT.
My third input formatter, the one for the long value, regards the last three characters as milliseconds of the second and everything before it as seconds since the epoch. The net result is that it parses milliseconds since the epoch. A DateTimeFormatterBuilder was required to build this formatter.
A no-lib solution
I admit that I hate to write this. I would really have hoped that you could avoid the notoriously troublesome SimpleDateFormat class and its long outdated cronies like Date. Since I understand that yours is a no-lib app, both of Joda-Time and ThreeTenABP seem out of the question. Sorry. In this case since there is no way that SimpleDateFormat can parse a long, my approach is to take a taste of the string to determine the format and choose my way of parsing based on that.
DateFormat inputIso = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX");
// This format resembles the output from Date.toString
DateFormat inputDatelike
= new SimpleDateFormat("EEE MMM dd HH:mm:ss ZZZ yyyy", Locale.ROOT);
DateFormat displayFormat
= DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.US);
displayFormat.setTimeZone(TimeZone.getDefault());
for (String inputString : new String[] {
"2020-01-25T21:59:27Z",
"Sat Jan 25 20:06:07 +0000 2020",
"1566777888999"
}) {
Date parsedDate;
if (Character.isDigit(inputString.charAt(0))) {
if (inputString.contains("-")) {
parsedDate = inputIso.parse(inputString);
} else {
// long number of millis
parsedDate = new Date(Long.parseLong(inputString));
}
} else {
parsedDate = inputDatelike.parse(inputString);
}
System.out.format("%-30s was parsed to %s%n",
inputString, displayFormat.format(parsedDate));
}
Output is exactly the same as before:
2020-01-25T21:59:27Z was parsed to Jan 25, 2020
Sat Jan 25 20:06:07 +0000 2020 was parsed to Jan 25, 2020
1566777888999 was parsed to Aug 26, 2019
Please be aware that here invalid input may cause either a NumberFormatException or a ParseException, so catch both. And only resort to this solution if there is no way that you can avoid it.
The line displayFormat.setTimeZone(TimeZone.getDefault()); is technically superfluous, but it makes explicit that the output depends on the time zone, and maybe more importantly, it tells you where you need to modify the code if you want output in a different time zone.
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. Only in this case use the method reference Instant::from instead of the constant Instant.FROM.
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.

How to get date time from UTC date time fromat?

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

Displaying the same date over DatePicker, ignoring device's TimeZone

I am displaying a date. The date varies with the Timezone of the device change. For example - Jan 01, 1960 for Timezone GMT +5.30 converts into Dec 31, 1959 for Timezone GMT -5.00. My requirement is that the date should be the same with any Timezone. I have converted my Date to UTC Date but still the date is changing according to Timezone. I have tried with few code as follows-
//Convering given date to UTC date using SimpleDateFormat
try {
final DateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
final Date date = sdf.parse(givenDate + "");
datePicker.setDate(date);
} catch (ParseException exception) {
exception.printStackTrace();
}
or
// Converting given date into GMT date using Timezone defference
final TimeZone tzLocal = TimeZone.getDefault();
final long gmtMillis = givenDate.getTime() - (tzLocal.getRawOffset());
final Date date = new Date();
date.setTime(gmtMillis);
datePicker.setDate(date);
I am using a custom DatePicker that has setDate(date) method (not android.widget.DatePicker).
I already have checked many similar Q&A but no luck. Thankyou
Not possible with java.util.Date
With java.util.Date you can’t. Despite the class name a Date does not represent a date. It is a point in time. So when the JVM’s default time zone may have changed since the Date was created, there is no way to detect which time zone was used when the Date was created. You can try all possible time zones, of course. This will typically give you two, occasionally three possible dates. Because it is never the same date in all time zones.
It may not be so bad as it sounds since the Date class is poorly designed and long outdated, so you shouldn’t use it anymore anyway.
Solution: java.time and ThreeTenABP
java.time, the modern Java date and time API, offers the LocalDate class. A LocalDate is a date without time of day and without time zone. So when you create a LocalDate worth Jan 01, 1960, it will always unambiguously be Jan 01, 1960.
LocalDate date = LocalDate.of(1960, Month.JANUARY, 1);
System.out.println(date);
There is nothing mysterious about the output:
1960-01-01
So the first suggestion is to base your custom DatePicker class on LocalDate rather than Date.
If you cannot afford to make that change right now, the short-term solution is to convert just before calling setDate (so only after the last change of default time zone has happened):
Instant startOfDayInDefaultZone = date.atStartOfDay(ZoneId.systemDefault())
.toInstant();
Date oldFashionedDate = DateTimeUtils.toDate(startOfDayInDefaultZone);
System.out.println(oldFashionedDate);
Output in my time zone was:
Fri Jan 01 00:00:00 CET 1960
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) the modern API comes built-in.
In 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.
In the above code I am using the DateTimeUtils from the backport for converting from Instant to Date. If your Android version has java.time built in, instead use Date.from(startOfDayInDefaultZone) for this conversion.
Links
All about java.util.Date
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.

Simple Date format gives wrong info from epoch timestamp

I found that this gives a wrong date. but how i can not solve it. please someone help me.
I am new in android Development.
Thanks in advance;
String timestamp = "1538970640";
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM 'at' hh:mm a z" );
String dateString = formatter.format(new Date(Long.parseLong(timestamp)));
This returns:
19 Jan at 01:29 AM GMT+06:oo
But it should be:
8 Oct at 9:50 AM GMT+06:00
The java.util.Date constructor accepts milliseconds since the Epoch, not seconds:
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.
The following code which uses ms is working:
String timestamp = "1538970640000"; // use ms NOT s
SimpleDateFormat formatter = new SimpleDateFormat("dd MMM 'at' hh:mm a z" );
String dateString = formatter.format(new Date(Long.parseLong(timestamp)));
08 Oct at 05:50 AM CEST
Demo
Part of the problem you were facing is that your date format omitted the year component, which was actually coming up as 1970.
java.time and ThreeTenABP
I recommend you use java.time, the modern Java date and time API, for your date and time work.
DateTimeFormatter timestampFormatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS)
.toFormatter();
DateTimeFormatter targetFormatter
= DateTimeFormatter.ofPattern("d MMM 'at' h:mm a z", Locale.ENGLISH);
String timestamp = "1538970640";
ZonedDateTime dateTime = timestampFormatter.parse(timestamp, Instant.FROM)
.atZone(ZoneId.systemDefault());
String dateString = dateTime.format(targetFormatter);
System.out.println(dateString);
Output is (when time zone is set to GMT+06:00, which by the way is not a true time zone):
8 Oct at 9:50 AM GMT+06:00
I am not very happy about converting date and time from one string format to another, though. In your app you should not handle date and time as strings but as proper date and time objects, for example Instant or ZonedDateTime. When you get a string from somewhere (a server?), parse it into a date-time object first thing. Only when you need to give string output, for example to the user, format your date and time into a string in the user’s time zone.
That said, java.time performs your conversion with just two formatters. No need to parse into a low-level long first.
Two more points:
Give your output formatter a locale to control the language used. Since AM and PM are hardly used in other languages than English, I figured that Locale.ENGLISH might be appropriate. You decide.
Since you want 8 Oct at 9:50 AM GMT+06:00, use just one d for day of month and one h for clock hour. Two digits will still be printed if the numbers go over 9, for example 10 Oct at 11:50 AM GMT+06:00.
What went wrong in your code?
Your number, 1538970640 (10 digits), denotes seconds since the epoch. This is the classical definition of a Unix timestamp. The Date constructor that you used expects milliseconds since the epoch. This is typical for the outdated Java date and time classes and methods. These years milliseconds since the epoch are typically 13 digits. As you can see, the modern Java date and time classes have better support for seconds here.
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 this case, instead of the constant Instant.FROM use the method references Instant::from.
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.

Getting GMT time with Android

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.

Categories

Resources