Date to timestring conversion one hour wrong - java

I have a Date, for example 2000-01-01T10:00:00Z . This stands for openinghours of a shop, so this means the shop opens at 10 o'clock. The other information is useless, it is a random date.
I only need to represent this as a string so: 10:00.
For this conversion i used a simple method:
public String dateToString(Date date){
SimpleDateFormat ft = new SimpleDateFormat ("HH:mm");
String time= ft.format(date);
return time;
}
I thought this should work, the capital HH for 24 hour representation of the hours. But when i run this code the return value is 11:00 !
Why is this, and how to prevent it? Does the format function take a look at my time zone and is this set wrong in the Date (i think my phone settings are mgt+1, cause i live in Holland)? And how to ignore this?

oke, found it!
Android converses a Date to the timezone of the device. I had to overrule that:
This works:
public String dateToString(Date date){
SimpleDateFormat ft = new SimpleDateFormat ("HH:mm");
ft.setTimeZone(TimeZone.getTimeZone("UTC"));
String time= ft.format(date);
return time;
}

The value 2000-01-01T10:00:00Z is not not at all “useless”. This describes an exact moment on the timeline, with a date, a time-of-day, and an offset-from-UTC which is UTC itself in this case.
ISO 8601
That string format is defined by the ISO 8601 standard. The Z on the end is short for Zulu and means UTC.
Instant
You can parse this string directly as a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds. That means up to nine (9) digits of a decimal fraction.
Instant instant = Instant.parse( "2000-01-01T10:00:00Z" );
The Instant class is only the basic building-block class in Java. For more flexibility we should either:
Assign the instant an offset-from-UTC (ZoneOffset) to get an OffsetDateTime.
Assign the instant a time zone (ZoneId) to get a ZonedDateTime.
What is the difference? A time zone is an offset plus a set of rules for handling anomalies such as Daylight Saving Time (DST).
OffsetDateTime
So if you truly wanted the time-of-day for this moment as seen in UTC, then assign an offset of UTC (ZoneOffset.UTC) to get an OffsetDateTime, and then extract a LocalTime object. LocalTime represents a time-of-day without a date and without a time zone.
OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );
LocalTime lt = odt.toLocalTime(); // 10:00:00
ZonedDateTime
If you want to see the same moment through the lens of another time zone, to see that particular region’s wall-clock time, specify a ZoneId. For example, that same moment in Québec would be 5 hours behind UTC.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z ); // 2000-01-01T05:00:00-05:00[America/Montreal]
LocalTime lt = zdt.toLocalTime(); // 05:00:00
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

Related

Unparseable Date error thrown when converting date to SimpleDateFormat

I am trying to convert a UTC string to just the hours and the minutes. I get the UTC string from an API but have given an example below of what it looks like.
When it gets to someDate it throws an Unparseable Date error and references the string setString.
Can anyone see what I am doing wrong here?
Example of how I am getting the date from UTC
String utcStr = "1521698232";
Date setSunrise = new Date(Long.parseLong(sunrise)*1000);
Trying to convert it to HH:mm
String setString = "Thu Mar 22 05:57:06 GMT+00:00 2018";
Date someDate = new SimpleDateFormat("EEE MMM d HH:mm:ss z'+00:00' yyyy").parse(setString);
Date printDate = new SimpleDateFormat("hh:mm").format(someDate);
tl;dr
You are working too hard, going in a roundabout manner. Also, you are using troublesome old obsolete classes. Also, I suspect you are ignoring the crucial issue of time zone.
Here is a much simpler and cleaner modern solution, with consideration for time zone.
Instant.ofEpochSecond( // Represent a moment in time in UTC, with a resolution of nanoseconds.
Long.parseLong( "1521698232" ) // Count of whole seconds since epoch of 1970-01-01T00:00:Z.
) // Returns a `Instant` object.
.atZone( // Apply a time zone (`ZoneId`) to adjust from UTC to the wall-clock time of the target audience.
ZoneId.of( "Asia/Kolkata" ) // Use only proper time zone names `continent/region`. Never use 3-4 letter codes such as `IST` or `EST`.
) // Produces a `ZonedDateTime` object.
.toLocalTime() // Extract only the time-of-day as a `LocalTime` object.
.truncatedTo( ChronoUnit.MINUTES ) // Lop off any seconds and fractional second.
.toString() // Generate a String in standard ISO 8601 format: HH:MM:SS.SSSSSSSSS
11:27
Count-from-epoch
convert a UTC string
No such thing as a “UTC string”.
Your input seems to represent a number of whole seconds since the epoch reference of first moment of 1970 UTC, 1970-01-01T00:00Z. This is sometimes referred to as Unix Time or POSIX Time.
ISO 8601
"Thu Mar 22 05:57:06 GMT+00:00 2018";
This is a terrible format for a date-time value.
Instead use standard ISO 8601 strings when exchanging date-time values as text. The java.time classes use ISO 8601 formats by default when parsing/generating strings.
Avoid legacy date-time classes
The Date and SimpleDateFormat classes are part of the troublesome old date-time classes that are now legacy, supplanted by the java.time classes.
Date is replaced by Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
String input = "1521698232" ; // Count of seconds since epoch reference of 1970-01-01T00:00Z.
long secondsSinceEpoch = Long.parseLong( input ) ;
Instant instant = Instant.ofEpochSecond( secondsSinceEpoch ) ;
instant.toString(): 2018-03-22T05:57:12Z
As discussed above, the Instant (like Date) is in UTC. If you ask for the time-of-day, you'll get a time-of-day in UTC. More likely you really want the time-of-day for that moment by the wall-clock time used by people in a certain region (a time zone).
A time zone is crucial in determining a date and time-of-day. For any given moment, the date and time-of-day varies around the globe by zone.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter pseudo-zones such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Pacific/Auckland" ) ;
Apply that zone to adjust from UTC, producing a ZonedDateTime object.
ZonedDateTime zdt = instant.atZone( z ) ;
zdt.toString(): 2018-03-22T18:57:12+13:00[Pacific/Auckland]
Now ask for the time-of-day. The resulting LocalTime objects lacks a date and lacks a time zone. It is just a time-of-day on a 24-hour clock.
LocalTime lt = zdt.toLocalTime() ;
If you only care about the hours and minutes, lop off and seconds and fractional second by truncating. Specify the level of truncation via the ChronoUnit class.
LocalTime ltTrunc = lt.truncatedTo( ChronoUnit.MINUTES ) ;
Generate a String in standard ISO 8601 format.
String output = ltTrunc.toString() ; // Generate a `String` in standard ISO 8601 format.
18:57
To generate a String in other formats, search Stack Overflow for DateTimeFormatter. You will find many discussions and examples.
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, and later
Built-in.
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
Much 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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
The +00:00 part is a UTC offset, and you can't treat as a literal (inside quotes, like you did). That's an important information, because it tells you how many hours ahead or behind UTC the date refers to (in this case, it's zero, so it's the same as UTC itself).
Another detail is that the day-of-week and month name are in English, so you should set a java.util.Locale in your class. If you don't use a locale, it'll use the JVM default and there's no guarantee that it'll always be English in all environments. If you're sure about the language used in the inputs, set the locale:
String setString = "Thu Mar 22 05:57:06 GMT+00:00 2018";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.ENGLISH);
Date someDate = parser.parse(setString);
For the output, 2 things:
using hh will print the hour-of-am-pm, which means values from 1 to 12. If you want the hours value from 0 to 23, use HH - this is all explained in the docs
the value of the hours will be converted to the device's default timezone, which means that not always will be the same of the input (in my case, my country is using -03:00 - 3 hours behind UTC - so the value of the hours is 2 AM.
To use the same offset in the input, you must set it in the formatter:
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
formatter.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
String printDate = formatter.format(someDate); // 05:57
To use java-time classes, the other answer by Basil tells you how to use this API in Android. I'd just like to add the similar code to parse your specific input:
String setString = "Thu Mar 22 05:57:06 GMT+00:00 2018";
DateTimeFormatter parser = DateTimeFormatter.ofPattern("EEE MMM d HH:mm:ss O yyyy", Locale.ENGLISH);
OffsetDateTime odt = OffsetDateTime.parse(setString, parser);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
String printDate = formatter.format(odt);

Convert UTC time to local time zone

I have to convert UTC time into user local time zone. Currently, I have the two parameters one is time in long format and another is time zone name in string format like "(UTC-05:00) Eastern Time (US and Canada), (UTC-06:00) Central Time (US and Canada)" etc.
So now using these two parameters I have to get date time in string format. I am facing the issue while I am trying to convert the date into a string because the SimpleDateFormat.format(...) will convert the date using its default time zone.
Below are the code portion
public static void main(String[] args)
{
long time = 1490112300000L;
System.out.println("UTC Time "+ convertLongToStringUTC(time));
String EST = "(UTC-05:00) Eastern Time (US and Canada)";
TimeZone timeZone1 = TimeZone.getTimeZone(EST);
System.out.println("EST "+ convertTimeZone(time, timeZone1));
String CST = "(UTC-06:00) Central Time (US and Canada)";
TimeZone timeZone2 = TimeZone.getTimeZone(CST);
System.out.println("CST "+ convertTimeZone(time, timeZone2));
String IST = "IST";
TimeZone timeZone = TimeZone.getTimeZone(IST);
System.out.println("IST "+ convertTimeZone(time, timeZone));
}
public String convertTimeZone(long time, TimeZone timeZone)
{
Date date = new Date(time);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
format.setTimeZone(timeZone);
return format.format(date);
}
public String convertLongToStringUTC(long time)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
String utcTime = sdf.format(new Date(time));
return utcTime;
}
Also let me know if we can achieve this using offset ?
Use this constructor
SimpleDateFormat(String pattern, Locale locale)
Constructs a SimpleDateFormat using the given pattern and the default
date format symbols for the given locale. Note: This constructor may
not support all locales. For full coverage, use the factory methods in
the DateFormat class.
Java Doc
tl;dr
Instant.ofEpochMilli( 1_490_112_300_000L )
.atOffset( ZoneOffset.of( "-05:00" ) )
Instant.ofEpochMilli( 1_490_112_300_000L )
.atZone( ZoneId.of( "America/New_York" ) )
Details
The Answer by Dennis is close. I will provide further information.
Your Question is not exactly clear about the inputs. I will assume your long integer number represents a moment in UTC.
An offset-from-UTC is an number of hours and minutes and seconds before or after UTC. In java.time, we represent that with a ZoneOffset.
While ZoneId technically works (as seen in code by Dennis), that is misleading as a zone is much more than an offset. A zone is a region’s history of various offsets that were in effect at different periods of history. A zone also includes any planned future changes such as DST cutovers coming in the next months.
ZoneOffset offset = ZoneOffset.of( 5 , 30 ); // Five-and-a-half hours ahead of UTC.
ZoneOffset offset = ZoneOffset.of( "+05:30" );
Tip: Always include the padding zero on the hours. While not always required in various protocols such as ISO 8601, I have seen software systems burp when encountering single-digit hours like +5:00.
If you know the intended time zone for certain, use it. A zone is always better than a mere offset as it brings all that historical information of other offsets for the past, present, and future.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-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( "Asia/Kolkata" );
I am guessing your number is a number of milliseconds since the epoch of 1970-01-01T00:00:00Z.
Instant instant = Instant.ofEpochMilli( 1_490_112_300_000L );
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
You can adjust into a time zone.
ZonedDateTime zdt = instant.atZone( z );
These issues have been covered many times in Stack Overflow. Hence the down-votes you are collecting (I am guessing). Please search Stack Overflow thoroughly before posting.
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.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
Using Java 8 you can do
OffsetDateTime dt = Instant.ofEpochMilli(System.currentTimeMillis())
.atOffset( ZoneOffset.of("-05:00"));
//In zone id you put the string of the offset you want

How to get time of the day, day of the week and month separately from sms query in android

I am extracting the date field from the sms table which returns the date as a time stamp,
but I wish to extract from the time stamp seprately
time of the day,
day of the week and
month of the year
I have read similar questions but none could help.
String date = cursor.getString(cursor.getColumnIndex("date"));
Long timestamp = Long.parseLong(date);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestamp);
Date finaldate = calendar.getTime();
String smsDate = finaldate.toString();
dateTextView.setText(smsDate);
int day= calendar.get(Calendar.DAY_OF_WEEK));
int month = calendar.get(Calendar.MONTH);
If you want to have the actual string value of month and the day, you can either use a switch to do that
Try the following,
String dayAsString = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
String monthAsString = calendar.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
Edit:
int hour12 = calendar.get(Calendar.HOUR); // 12
int hour24 = calendar.get(Calendar.HOUR_OF_DAY); //24
You can do calendar.MONTH, calendar.DAY and so.
you should use Joda Time:
http://www.joda.org/joda-time/
String date = cursor.getString(cursor.getColumnIndex("date"));
Long timestamp = Long.parseLong(date);
DateTime dateTime = new DateTime(timestamp);
int dayOfWeek = dateTime.getDayOfWeek();
int monthOfYear = dateTime1.getMonthOfYear();
tl;dr
Instant.ofEpochMilli( myCountOfMillis ) // Parse a count of milliseconds since first moment of 1970 in UTC.
.atZone( ZoneId.of( "Pacific/Auckland" ) ) // Instantiate a `ZonedDateTime` object, having adjusted from UTC into a particular time zone.
.getDayOfWeek() // Extract a `DayOfWeek` enum object.
.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) // Or Locale.US, Locale.ITALY, etc. to determine human language and cultural norms in generating a localized string to represent this day-of-week.
lundi
java.time
Modern approach uses the java.time classes.
Assuming your long integer is a count of milliseconds since the epoch reference of first moment of 1970 in UTC, 1970-01-01T00:00Z, instantiate a Instant. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = Instant.ofEpochMilli( myCountOfMillis ) ;
A time zone is crucial in determining a date. 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, 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 3-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" ) ;
Apply your desired/expected time zone to the Instant to get a ZonedDateTime. Same moment, same point on the timeline, but with a different wall-clock time.
ZonedDateTime zdt = instant.atZone( z ) ;
Now you are in a position to interrogate for the parts of month, day-of-week, and time-of-day.
Month month = zdt.getMonth() ; // Get a `Month` enum object.
int m = zdt.getMonthValue() ; // Get an integer 1-12 for January-December.
DayOfWeek dow = zdt.getDayOfWeek() ; // Get a `DayOfWeek` enum object.
int dowNumber = zdt.getDayOfWeek().getValue() ; // Get a number for the day-of-week, 1-7 for Monday-Sunday per ISO 8601 standard.
String dowName = zdt.getDayOfWeek().getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH ) ; // Generate a localized string representing the name of this day-of-week.
LocalTime lt = zdt.toLocalTime() ; // Get a time-of-day object, without date, without time zone.
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.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
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
Much 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, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

SimpleDateFormat specify timeZone [duplicate]

I am working on a project that fetches Date/Time from backend in IST(Indian standard Time) as shown "2013-01-09T19:32:49.103+05:30". However when i parse it using following DateFormat
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
followed by parsing..
Date date = sdf.parse("2013-01-09T19:32:49.103+05:30");
System.out.println("XYZ ==============>"+date);
its Displaying date in GMT format as output i.e
Wed Jan 09 14:02:49 GMT+00:00 2013.
I have tried it using TimeZone class as..
TimeZone timeZone=TimeZone.getTimeZone("IST");
sdf.setTimeZone(timeZone);
but no effect..
How could i get a Date class Object having Date in IST format instead of GMT...
Please provide an appropriate solution..
EDIT:
This is how Code Looks Like:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
TimeZone timeZone=TimeZone.getTimeZone("IST");
sdf.setTimeZone(timeZone);
Date date = sdf.parse("2013-01-09T19:32:49.103+05:30");
String formattedDate=sdf.format(date);
System.out.println("XYZ ==============>"+formattedDate);
Date does not have any time zone. It is just a holder of the number of milliseconds since January 1, 1970, 00:00:00 GMT. Take the same DateFormat that you used for parsing, set IST timezone and format your date as in the following example
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
Date date = sdf.parse("2013-01-09T19:32:49.103+05:30");
sdf.setTimeZone(TimeZone.getTimeZone("IST"));
System.out.println(sdf.format(date));
output
2013-01-09T19:32:49.103+05:30
Note that XXX pattern is used for ISO 8601 time zone (-08:00) since 1.7. If you are in 1.6 try Z. See SimpleDateFormat API for details of format patterns
How could i get a Date class Object having Date in IST format instead of GMT...
You can't. Date doesn't have a format or a time zone. It simply represents a number of milliseconds since the Unix epoch of midnight on January 1st 1970 UTC. Instead, Date.toString() always uses the default time zone.
To use a specific format and time zone, use DateFormat instead of Date.toString(). You can set the time zone with DateFormat.setTimeZone() and then convert a Date to a String using DateFormat.format(). DateFormat itself has some factory methods for creation, or you can use SimpleDateFormat if you want to specify a particular pattern.
As Abu says, Joda Time is a much better date/time API than the built-in one, although for just formatting a date/time the standard library doesn't do a bad job. Just note that DateFormat and its subclasses are generally not thread-safe.
tl;dr
OffsetDateTime.parse( "2013-01-09T19:32:49.103+05:30" ) // Parsed.
.toInstant() // Adjusted to UTC.
See live code in IdeOne.com.
ISO 8601
Your input string of 2013-01-09T19:32:49.103+05:30 happen to be in standard ISO 8601 format. The +05:30 at the end indicates an offset-from-UTC of five and a half hours ahead, used in India.
java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.
The java.time classes happen to use ISO 8601 formats by default when parsing/generating Strings representing date-time values. So no need to specify a formatting pattern at all.
As your input represents a moment on the timeline with an offset-from-UTC, we parse as a OffsetDateTime object.
OffsetDateTime odt = OffsetDateTime.parse( "2013-01-09T19:32:49.103+05:30" );
odt.toString(): 2013-01-09T19:32:49.103+05:30
To obtain a simple object in UTC value, extract an Instant. This Instant class is a basic building-block class of java.time. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
You can think of OffsetDateTime as an Instant plus a ZoneOffset.
Instant instant = odt.toInstant(); // UTC.
When calling toString, a String object is generated in standard ISO 8601 format. The Z on the end is short for Zulu and means UTC.
instant.toString(): 2013-01-09T14:02:49.103Z
An Instant is limited in various ways such as when generating Strings in various formats. So you may want to work with an OffsetDateTime adjusted into UTC as its offset; an offset-of-zero, in other words. The ZoneOffset class holds a constant for UTC, ZoneOffset.UTC.
OffsetDateTime odtUtc = odt.withOffsetSameInstant( ZoneOffset.UTC );
You can also apply an offset (or time zone) to an Instant. Call atOffset or atZone.
The Instant class is the basic building-block class of java.time. Likely to be used often in your code as best practice is to do most of your work in UTC.
OffsetDateTime odt = instant.atOffset( ZoneOffset.ofHoursMinutes( 5 , 30 ) );
Time zone
Note that an offset-from-UTC is not a time zone. A time zone is an offset plus a set of rules, past and present, for handling anomalies such as Daylight Saving Time (DST). So a time zone is always preferable to a mere offset if you are indeed sure of the correct zone.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
If you know the intended time zone, apply a ZoneId to get a ZonedDateTime object. But never assume without verifying with the source of your input data. Many different zones may share a particular offset. For example, in the case of our input here, the offset +05:30 happens to be used today in both India (Asia/Kolkata) and Sri Lanka (Asia/Colombo). Those two time zones may have different rules for different anomalies in their past, present, or future.
ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = odt.atZoneSameInstant( z );
The toString method of ZonedDateTime extends standard ISO 8601 format in a wise way by appending the name of the time zone is square brackets. In this case, [Asia/Kolkata].
zdt.toString(): 2013-01-09T19:32:49.103+05:30[Asia/Kolkata]
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 java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You can do this simply by use of Calender class. Please check below snippets:
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
calendar.setTimeInMillis(<--time stamp-->);
//calendar.setTime(<--date object of gmt date-->);
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy 'at' hh:mm a");
sdf.setTimeZone(TimeZone.getDefault());
String result=sdf.format(calendar.getTime());

How to save and retrieve Date in SharedPreferences

I need to save a few dates in SharedPreferences in android and retrieve it. I am building reminder app using AlarmManager and I need to save list of future dates. It must be able to retrieve as milliseconds. First I thought to calculate time between today now time and future time and store in shared preference. But that method is not working since I need to use it for AlarmManager.
To save and load accurate date, you could use the long (number) representation of a Date object.
Example:
//getting the current time in milliseconds, and creating a Date object from it:
Date date = new Date(System.currentTimeMillis()); //or simply new Date();
//converting it back to a milliseconds representation:
long millis = date.getTime();
You can use this to save or retrieve Date/Time data from SharedPreferences like this
Save:
SharedPreferences prefs = ...;
prefs.edit().putLong("time", date.getTime()).apply();
Read it back:
Date myDate = new Date(prefs.getLong("time", 0));
Edit
If you want to store the TimeZone additionaly, you could write some helper method for that purpose, something like this (I have not tested them, feel free to correct it, if something is wrong):
public static Date getDate(final SharedPreferences prefs, final String key, final Date defValue) {
if (!prefs.contains(key + "_value") || !prefs.contains(key + "_zone")) {
return defValue;
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(prefs.getLong(key + "_value", 0));
calendar.setTimeZone(TimeZone.getTimeZone(prefs.getString(key + "_zone", TimeZone.getDefault().getID())));
return calendar.getTime();
}
public static void putDate(final SharedPreferences prefs, final String key, final Date date, final TimeZone zone) {
prefs.edit().putLong(key + "_value", date.getTime()).apply();
prefs.edit().putString(key + "_zone", zone.getID()).apply();
}
You can do this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.US);
To save a date:
preferences .edit().putString("mydate", sdf.format(date)).apply();
To retrieve:
try{
Date date = sdf.parse(preferences.getString("myDate", "defaultValue"));
} catch (ParseException e) {
e.printStackTrace();
}
Hope it help.
tl;dr
The modern approach uses java.time classes and ISO 8601 strings.
Reading.
Instant // Represent a moment in UTC with a resolution of nanoseconds.
.ofEpochMilli(
Long.getLong( incomingText )
) // Returns a `Instant` object.
.atZone( // Adjust from UTC to some time zone. Same moment, same point on the timeline, different wall-clock time.
ZoneId.of( "Europe/Paris" )
) // Returns a `ZonedDateTime` object.
Writing.
ZonedDateTime
.of(
LocalDate.of( 2018 , Month.JANUARY , 23 ) ,
LocalTime.of( 15 , 35 ) ,
ZoneId.of( "Europe/Paris" )
) // Returns a `ZonedDateTime` object.
.toInstant() // Returns an `Instant`. Adjust from a time zone to UTC. Same moment, same point on the timeline, different wall-clock time.
.toEpochMilli() // Returns a `long` integer number primitive. Any microseconds or nanoseconds are ignored, of course.
If your alarm manager has not yet been modernized to handle java.time objects, convert between legacy & modern classes using new methods added to the old classes.
java.util.Date d = java.util.Date.from( instant ) ;
…and…
Instant instant = d.toInstant() ;
java.time
The troublesome old date-time classes were supplanted by the java.time classes.
For a moment in UTC, with a resolution of nanoseconds, use Instant.
Instant instant = Instant.now() ; // Capture the current moment in UTC.
You want only milliseconds for your needs, so truncate any microseconds & nanoseconds.
Instant instant = Instant.now().truncatedTo( ChronoUnit.MILLIS ) ;
To determine a moment by date and time-of-day requires a time zone. A time zone is crucial in determining a date. 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 3-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" ) ;
LocalDate today = LocalDate.now( z ) ;
If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the JVM’s current default is applied implicitly. Better to be explicit, as the default may be changed at any moment during runtime by any code in any thread of any app within the JVM.
ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.
Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.
LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.
Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety.
LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;
Combine with a time-of-day, a LocalTime.
LocalTime lt = LocalTime.of( 14 , 0 ) ;
Wrap it all together as a ZonedDateTime object.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust to UTC by extracting a Instant.
Instant instant = zdt.toInstant() ;
Extract your desired count-of-milliseconds since the epoch reference of first moment of 1970 in UTC. Again, be aware that any micros/nanos in your Instant will be ignored when extracting milliseconds.
long milliseconds = instant.toEpochMilli() ; // Be aware of potential data loss, ignoring any microseconds or nanoseconds.
Read those milliseconds back from storage as text using the Long class.
long milliseconds = Long.getLong( incomingText ) ;
Instant instant = Instant.ofEpochMilli( milliseconds ) ;
To see that moment through the lens of the wall-clock time used by the people of a particular region (a time zone), apply a ZoneId to get a ZonedDateTime.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
To generate text representing that value, use DateTimeFormatter.ofLocalizedDateTime to automatically localize.
Tip: Consider writing your date-time values to storage in standard ISO 8601 format rather than as a count-of-milliseconds. The milliseconds cannot be read meaningfully by humans, making debugging & monitoring tricky.
String output = instant.toString() ;
2018-10-05T20:28:48.584Z
Instant instant = Instant.parse( 2018-10-05T20:28:48.584Z ) ;
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….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories