SimpleDateFormat specify timeZone [duplicate] - java

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

Related

Java: Calculate month end date based on timezone

I have method to find month end date based on the timezone.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
calendar.set(
Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
);
System.out.println(calendar.getTime());`
It displays output: Thu Aug 30 18:04:54 PDT 2018.
It should, however, give me an output in CET.
What am I missing?
The Calendar.getTime() method returns a Date object, which you then printed in your code. The problem is that the Date class does not contain any notion of a timezone even though you had specified a timezone with the Calendar.getInstance() call. Yes, that is indeed confusing.
Thus, in order to print a Date object in a specific timezone, you have to use the SimpleDateFormat class, where you must call SimpleDateFormat.setTimeZone() to specify the timezone before you print.
Here's an example:
import java.util.Calendar;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class TimeZoneTest {
public static void main(String argv[]){
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println("calendar.getTime(): " + calendar.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
System.out.println("sdf.format(): " + sdf.format(calendar.getTime()));
}
}
Here is the output on my computer:
calendar.getTime(): Fri Aug 31 01:40:17 UTC 2018
sdf.format(): 2018-Aug-31 03:40:17 CEST
This is because Date object doesn't have timezone as part of its state, and getTime() actually returns a date which corresponds to the JVM's timezone, instead you need SimpleDateFormat to format and print the date in your required timezone.
If you try adding the following line of code, you could see that the timezone in the calendar is actually CET.
System.out.println(calendar.getTimeZone().getDisplayName());
tl;dr
YearMonth // Represent a year-month without day-of-month.
.now( // Capture the current year-month as seen in the wall-clock time used by the people of a particular region (a time zone).
ZoneId.of( "Africa/Tunis" ) // Specify your desired time zone. Never use 3-4 letter pseudo-zones such as `CET`.
) // Returns a `YearMonth` object.
.atEndOfMonth() // Determine the last day of this year-month. Returns a `LocalDate` object.
.atStartOfDay( // Let java.time determine the first moment of the day. Not necessarily 00:00:00, could be 01:00:00 or some other time-of-day because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "Africa/Tunis" )
) // Returns a `ZonedDateTime` object, representing a date, a time-of-day, and a time zone.
java.time
You are using the terrible old Calendar class that was supplanted years ago but the modern java.time classes.
LocalDate
If you need only a date, use LocalDate class. Then the time zone is irrelevant for your output.
But time zone is very relevant for determining the current date. For any given moment, the date 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 abbreviation such as CET or IST as they are not true time zones, not standardized, and not even unique(!).
ZoneId z = ZoneId.of( "Europe/Paris" ) ; // Or "Africa/Tunis" etc.
LocalDate today = LocalDate.now( z ) ; // Capture the current date as seen by the wall-clock time used by the people of a certain region (a time zone).
YearMonth
Get the month for that date. Represent a year-month with, well, YearMonth.
YearMonth ym = YearMonth.from( today ) ;
Or skip the LocalDate.
YearMonth ym = YearMonth.now( z ) ;
Get the end of the month.
LocalDate endOfThisMonth = ym.atEndOfMonth() ;
ISO 8601
To generate a String representing that LocalDate object’s value, call toString. The default format is taken from the ISO 8601 standard. For a date-only value that will be YYYY-MM-DD such as 2018-01-23.
String output = endOfThisMonth.toString() ;
If you need another format, use DateTimeFormatter class. Search Stack Overflow for many examples and discussions.
Moment
If you need a moment, you can add a time-of-day and time zone to your LocalDate to get a ZonedDateTime. Or let ZonedDateTime determine the first moment of the day (which is not always 00:00:00!).
ZonedDateTime zdt = LocalDate.atStartOfDay( z ) ;
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, 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.

Java: parse ISO_DATE / ISO_OFFSET_DATE

For a REST web service, I need to return dates (no time) with a time zone.
Apparently there is no such thing as a ZonedDate in Java (only LocalDate and ZonedDateTime), so I'm using ZonedDateTime as a fallback.
When converting those dates to JSON, I use DateTimeFormatter.ISO_OFFSET_DATE to format the date, which works really well:
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE;
ZonedDateTime dateTime = ZonedDateTime.now();
String formatted = dateTime.format(formatter);
2018-04-19+02:00
However, attempting to parse back such a date with...
ZonedDateTime parsed = ZonedDateTime.parse(formatted, formatter);
... results in an Exception:
java.time.format.DateTimeParseException: Text '2018-04-19+02:00' could not be parsed: Unable to obtain ZonedDateTime from TemporalAccessor: {OffsetSeconds=7200},ISO resolved to 2018-04-19 of type java.time.format.Parsed
I also tried ISO_DATE and ran into the same problem.
How can I parse such a zoned date back?
Or is there any other type (within the Java Time API) I'm supposed to use for zoned dates?
The problem is that ZonedDateTime needs all the date and time fields to be built (year, month, day, hour, minute, second, nanosecond), but the formatter ISO_OFFSET_DATE produces a string without the time part.
When parsing it back, there are no time-related fields (hours, minutes, seconds) and you get a DateTimeParseException.
One alternative to parse it is to use a DateTimeFormatterBuilder and define default values for the time fields. As you used atStartOfDay in your answer, I'm assuming you want midnight, so you can do the following:
DateTimeFormatter fmt = new DateTimeFormatterBuilder()
// date and offset
.append(DateTimeFormatter.ISO_OFFSET_DATE)
// default values for hour and minute
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.toFormatter();
ZonedDateTime parsed = ZonedDateTime.parse("2018-04-19+02:00", fmt); // 2018-04-19T00:00+02:00
Your solution also works fine, but the only problem is that you're parsing the input twice (each call to formatter.parse will parse the input again). A better alternative is to use the parse method without a temporal query (parse only once), and then use the parsed object to get the information you need.
DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE;
// parse input
TemporalAccessor parsed = formatter.parse("2018-04-19+02:00");
// get data from the parsed object
LocalDate date = LocalDate.from(parsed);
ZoneId zone = ZoneId.from(parsed);
ZonedDateTime restored = date.atStartOfDay(zone); // 2018-04-19T00:00+02:00
With this solution, the input is parsed only once.
tl;dr
Use a time zone (continent/region) rather than a mere offset-from-UTC (hours-minutes-seconds). For any particular zone, the offset is likely to change over time.
Combine the two to determine a moment.
LocalDate.parse(
"2018-04-19"
)
.atStartOfDay(
ZoneId.of( "Europe/Zurich" )
) // Returns a `ZonedDateTime` object.
2018-04-19T00:00+02:00[Europe/Zurich]
From your REST service, either:
Return the date and zone separately (either with a delimiter or as XML/JSON), or,
Return the start of day as that is likely the intended outcome of a date with a time zone.
Separate your text inputs
The solution in the Answer by Walser is effectively treating the string input as a pair of string inputs. First the date-only part is extracted and parsed. Second, the offset-from-UTC part is extracted and parsed. So, the input is parsed twice, each time ignoring the opposite half of the string.
I suggest you make this practice explicit. Track the date as one piece of text, track the offset (or, better, a time zone) as another piece of text. As the code in that other Answer demonstrates, there is no real meaning to a date with zone until you take the next step of determining an actual moment such as the start of day.
String inputDate = "2018-04-19" ;
LocalDate ld = LocalDate.parse( inputDate ) ;
String inputOffset = "+02:00" ;
ZoneOffset offset = ZoneOffset.of( inputOffset) ;
OffsetTime ot = OffsetTime.of( LocalTime.MIN , offset ) ;
OffsetDateTime odt = ld.atTime( ot ) ; // Use `OffsetDateTime` & `ZoneOffset` when given a offset-from-UTC. Use `ZonedDateTime` and `ZoneId` when given a time zone rather than a mere offset.
odt.toString(): 2018-04-19T00:00+02:00
As you can see, the code is simple, and your intent is obvious.
And no need to bother with any DateTimeFormatter object nor formatting patterns. Those inputs conform with ISO 8601 standard formats. The java.time classes use those standard formats by default when parsing/generating strings.
Offset versus Zone
As for applying the date and offset to get a moment, you are conflating a offset-from-UTC with a time zone. An offset is simply a number of hours, minutes, and seconds. No more, no less. In contrast, a time zone is a history of the past, present, and future changes in offset used by the people of a particular region.
In other words, the +02:00 happens to be used by many time zones on many dates. But in a particular zone, such as Europe/Zurich, other offsets may be used on other dates. For example, adopting the silliness of Daylight Saving Time (DST) means a zone will be spending half the year with one offset and the other half with a different offset.
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( "Europe/Zurich" ) ;
ZonedDateTime zdt = ld.atStartOfDay( z ) ;
zdt.toString(): 2018-04-19T00:00+02:00[Europe/Zurich]
So I suggest you track two strings of input:
Date-only (LocalDate): YYYY-MM-DD such as 2018-04-19
Proper time zone name (ZoneId): continent/region such as Europe/Zurich
Combine.
ZonedDateTime zdt =
LocalDate.parse( inputDate )
.atStartOfDay( ZoneId.of( inputZone ) )
;
Note: The ZonedDateTime::toString method generates a String in a format that wisely extends the standard ISO 8601 format by appending the name of the time zone in square brackets. This rectifies a huge oversight made by the otherwise well-designed standard. But you can only return such a string by your REST service if you know your clients can consume it.
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, 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.
I found the solution (using TemporalQueries):
parse the date and zone separately, and restore the zoned date using that information:
LocalDate date = formatter.parse(formatted, TemporalQueries.localDate());
ZoneId zone = formatter.parse(formatted, TemporalQueries.zone());
ZonedDateTime restored = date.atStartOfDay(zone);

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

DateFormat format method doesn't display a parsed date to a particular TimeZone

I converted a date string to Date by SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").parse(DateinString).
Here instead of converting to UTC it is converting to my Local TimeZone. I checked it by displaying this parsed date through format method of DateFormat.
So I have to re format it back to UTC.Now when I am trying to display this parsed date to UTC TimeZone through the same format method, it is still displaying in local TimeZone. Following is my code to format the parsed date to UTC-
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
cal.setTime(alreadyParsedDateTime); //
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(cal.getTime()));
My sample date string is "2015-12-23T15:00:00-0800"
After parse -- alreadyParsedDateTime.toString():: Thu Dec 24 04:30:00 IST 2015
After parse --
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(alreadyParsedDateTime)):: 2015-12-24T04:30:00
After the above mentioned re format of the parsed date to UTC --
System.out.println(new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").format(cal.getTime())):: 2015-12-24T04:30:00
Expected date format is:: 2015-12-23T23:00:00
I don't know why the format method not working in an expected way or there is any trick to do the same. Kindly help..
There are two different topics here; parsing and formatting.
1. Parsing
SimpleDateFormat.parse() will try to parse the timezone from the supplied date string. If the date string you are parsing does not include an explicit timezone, then the "default" timezone on the SimpleDateFormat object will be used. You can set the default time zone with the setTimeZone() method. Please see the API docs for SimpleDateFormat.parse() and DateFormat.setTimeZone() for reference.
Here is an example that shows how the parsing is influenced by the timezone set with setTimeZone():
String dateString = "2015.12.10 13:58:18";
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf1.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date1 = sdf1.parse(dateString);
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss");
sdf2.setTimeZone(TimeZone.getTimeZone("EST"));
Date date2 = sdf2.parse(dateString);
// Shows that the parsing honours time zone -- will print:
// Thu Dec 10 14:58:18 CET 2015 (original date was parsed as GMT)
// Thu Dec 10 19:58:18 CET 2015 (original date was parsed as EST)
System.out.println(date1);
System.out.println(date2);
2. Formatting
Assuming that the date has been parsed correctly, then your problem is with the formatting. You need to set the timezone for the actual SimpleDateFormat object that you are using for formatting. I modified your code to do this and it will now print what you expet:
Calendar cal = Calendar.getInstance();
cal.setTime(alreadyParsedDateTime);
SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf3.setTimeZone(TimeZone.getTimeZone("UTC"));
// Prints: 2015-12-23T23:00:00 for your example date string
System.out.println(sdf3.format(cal.getTime()));
tl;dr
Current moment in UTC.
Instant.now() // Capture current moment in UTC.
.toString() // Generate string in standard ISO 8601 format.
2018-02-11T22:13:28.650328Z
Adjust into another time zone.
instant.atZone( // Apply a `ZoneId` to `Instant` object to get a `ZonedDateTime` object.
ZoneId.of( "Pacific/Auckland" )
).toString()
2018-02-12T11:13:28.650328+13:00[Pacific/Auckland]
Or capture current moment directly into that zone.
ZonedDateTime.now( // Capture current moment as seen on the wall-clock time of the people in a particular region.
ZoneId.of( "Pacific/Auckland" )
).toString() // Generate string in standard ISO 8601 format, wisely extended by appending the name of the time zone in square brackets.
2018-02-12T11:13:28.650328+13:00[Pacific/Auckland]
Details
The Answer by Grodriguez is correct but outdated.
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.
Your input string complies with the ISO 8601 formatting standard. The java.time classes use these formats by default when parsing/generating strings. So no need to specify a formatting pattern.
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).
Capture the current moment in UTC.
Instant instant = Instant.now() ; // Current moment in UTC.
To view that same simultaneous moment through the lens of a wall-clock time used by the people of another region (time zone), apply a ZoneId to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;
Note that we are working with smart objects here, not dumb strings. Do not conflate the date-time objects with mere strings that may represent their values textually.
If you want to generate a String in standard ISO 8601 format, call the toString method.
String outputA = instant.toString() ;
String outputB = zdt.toString() ;
To generate strings in other formats, use the DateTimeFormatter or DateTimeFormatterBuilder classes. Both are covered extensively on Stack Overflow, so search for more info.
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.
With a JDBC driver complying with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings or 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, 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