Java, How to change GMT time to local time? - java

Server sends me time like this:
2012-06-08 17:00:00 +0100
I need to change it like HH:MM based on local time. For example this time is what time at Japan, India, US and etc.
How can I do this? Thanks

Option 1: using java.util.Date/Calendar:
First you need to parse the value to a Date, then reformat it in the format and time zone
you're interested in:
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z",
Locale.US);
Date date = inputFormat.parse(inputText);
// Potentially use the default locale. This will use the local time zone already.
SimpleDateFormat outputFormat = new SimpleDateFormat("HH:mm", Locale.US);
String outputText = outputFormat.format(date);
Option 2: using Joda Time
Joda Time is a much better date/time library for Java.
DateTimeFormatter inputFormatter = DateTimeFormat
.forPattern("yyyy-MM-dd HH:mm:ss Z")
.withLocale(Locale.US);
DateTime parsed = inputFormatter.parseDateTime(inputText);
DateTimeFormatter outputFormatter = DateTimeFormat
.forPattern("HH:mm")
.withLocale(Locale.US)
.withZone(DateTimeZone.getDefault());
String outputText = outputFormatter.print(parsed);
Note that you should only convert to/from string representations when you really need to. Otherwise, use the most appropriate type based on your usage - this is where Joda Time really shines.

Use JodaTime. It's far better and safer than Java's Date and Time API. There are a lot of methods that return a LocalTime object (HH:MM).
As an example, new DateTime(your date time).toLocalTime();

java.util.Date is always in UTC. What makes you think it's in local time? I suspect the problem is that you're displaying it via an instance of Calendar which uses the local timezone, or possibly using Date.toString() which also uses the local timezone.
If this isn't the problem, please post some sample code.
I would, however, recommend that you use Joda Time anyway, which offers a much clearer API.

The other Answers are correct but outdated. Use java.time classes instead.
tl;dr
ZonedDateTime zdt_Kolkata = OffsetDateTime.parse( "2012-06-08 17:00:00 +0100" , DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss Z" ) ).atZone( ZoneId.of( "Asia/Kolkata" ) );
Using java.time
Define a DateTimeFormatter formatting pattern to match your input String.
String input = "2012-06-08 17:00:00 +0100";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "yyyy-MM-dd HH:mm:ss Z" );
OffsetDateTime
Parse the String as an OffsetDateTime object that represents the +0100 in your input which means “one hour ahead of UTC”.
OffsetDateTime odt = OffsetDateTime.parse( input , f );
ZonedDateTime
Apply a ZoneId to produce a ZonedDateTime for any desired time zone. Specify a proper time zone name. 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 zoneId_Kolkata = ZoneId.of( "Asia/Kolkata" ); // India
ZonedDateTime zdt_Kolkata = odt.atZone( zoneId_Kolkata );
…and another…
ZoneId zoneId_Montréal = ZoneId.of( "Asia/Montreal" ); // Québec Canada
ZonedDateTime zdt_Montréal = odt.atZone( zoneId_Montréal );
Instant
For UTC, extract an Instant object. The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = zdt_Montréal.toInstant();
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome 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.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.

Related

Convert CST time zone to required Time zone Java

I need to convert a Date which is in CST to required time zone. I will get Date as String like "11/5/2018 12:54:20" which is in CST time zone. I have to convert this to a time zone which is passed as a parameter. suppose lets take it as "GMT+0530".
The result for the above date ideally "Nov 06 2018 00:24:20"
I have tried the below code which returned the passed date(11/05/2018 12:54:20) as same instead of(Nov 06 2018 00:24:20) . I have executed this on a system which has IST time zone.
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT-0600"));
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+0530"));
System.out.println(sdf2.format(sdf.parse("11/5/2018 12:54:20").getTime()));
Edit:
Answer:
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( "11/5/2018 12:54:20" , f ) ;
ZoneId z = ZoneId.of( "GMT-0600" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
System.out.println(zdt);
ZoneId zKolkata = ZoneId.of( "GMT+0530" ) ;
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( zKolkata ) ;
System.out.println(zdtKolkata);
tl;dr
LocalDateTime // Represent a date and a time-of-day, without offset nor zone. So *not* a moment, *not* a point on the timeline.
.parse(
"11/5/2018 12:54:20" ,
DateTimeFormatter.ofPattern( "d/M/uuuu HH:mm:ss" ) // Define a formatting pattern to match your input string.
) // Returns a `LocalDateTime`.
.atZone( // Assign a time zone, to give meaning to the `LocalDateTime` object, making it a `ZonedDateTime` object.
ZoneId.of( "America/New_York" ) // Define a time zone properly with `Continent/Region` naming, never 2-4 letter pseudo-zones such as CST or IST.
) // Returns a `ZonedDateTime` object.
.withZoneSameInstant( // Adjust from New York time to Kolkata time. Some moment, different wall-clock time.
ZoneId.of( "Asia/Kolkata" )
) // Returns another `ZonedDateTime` object rather than altering (“mutating”) the original, per Immutable Objects pattern.
.toString() // Generate text in standard ISO 8601 format, wisely extended to append the name of the time zone in square brackets.
2018-05-11T22:24:20+05:30[Asia/Kolkata]
java.time
You are using terrible old classes, now supplanted by java.time classes.
Parse your input string as a LocalDateTime because it lacks any indication of offset-from-UTC or time zone.
Define a formatting pattern to match your input.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "d/M/uuuu HH:mm:ss" ) ;
LocalDateTime ldt = LocalDateTime.parse( "11/5/2018 12:54:20" , f ) ;
ldt.toString(): 2018-05-11T12:54:20
You say this was intended for CST. Did you mean China Standard Time? Or Central Standard Time in North America?
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as CST or EST or IST as they are not true time zones, not standardized, and not even unique(!).
I will assume you meant something like New York time.
ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
zdt.toString(): 2018-05-11T12:54:20-04:00[America/New_York]
And apparently you want to see this same moment through the lens of the wall-clock time used by the people of a different region, a different time zone. By IST did you mean Irish Standard Time? Or India Standard Time? Again, use real time zones not these 2-4 character pseudo-zones.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdtKolkata = zdt.withZoneSameInstant( zKolkata ) ;
zdtKolkata.toString(): 2018-05-11T22:24:20+05:30[Asia/Kolkata]
To see the same moment in UTC, extract a Instant.
Instant instant = zdtKolkata.toInstant() ;
instant.toString(): 2018-05-11T16:54:20Z
All three of these ( zdt, zdtKolkata, instant ) all represent the same moment, the same point on the timeline.
In contrast, the ldt as a LocalDateTime object does not represent a moment, is not a point on the timeline. It held no real meaning until you assigned it a time zone to give it a context. Until assigning that zone, we do not know if meant noon hour in Australia or in Africa, or in America. It could have meant any of about 26-27 hours, the range of time zones around the globe.
ISO 8601
Rather than inventing your own formats for exchanging date-time values as text, use the standard ISO 8601 formats.
The java.time classes conveniently use ISO 8601 formats by default when generating/parsing strings.
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.
You are setting the timezone of sdf twice and not setting timezone of sdf2 and thus getting incorrect results. Also, you don't need to call getTime() when passing object to DateFormat::format().
Here is a fixed version of your code:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
TimeZone cstTimeZone = TimeZone.getTimeZone("CST");
sdf.setTimeZone(cstTimeZone);
SimpleDateFormat sdf2 = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
sdf2.setTimeZone(TimeZone.getTimeZone("GMT+0530"));
System.out.println(sdf2.format(sdf.parse("11/5/2018 12:54:20")));
Note that the classes you are using are quite old and since version 8, Java provides new Date and Time APIs.

Current time not getting converted into MST timezone

I'm trying to convert current time in MST using below code
DateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
TimeZone toTimeZone = TimeZone.getTimeZone("MST");
sdf.setTimeZone(toTimeZone);
Date date = new Date();
String strDate = sdf.format(date.getTime());
strDate displaying correct MST time, but after parsing it is giving wrong date time.
Date currentDate = sdf.parse(strDate);
I want current MST time in Date format not in string.
A java.util.Date object does not have a concept of time zone.
There is no way to set a timezone for a Date
There is no way to change the timezone of a Date object
A Date object created with the new Date() default constructor will be initialised with the current time in the system default timezone
All you did is add a time zone information for the formatting part... setTimeZone does not convert anything.
tl;dr
ZonedDateTime zdt = LocalDateTime.parse( input , DateTimeFormatter.forPattern( "dd/MM/uuuu hh:mm:ss" ) ).atZone( ZoneId.of( "America/Denver" ) );
Avoid legacy date-time classes
You are using old outmoded troublesome legacy date-time classes.
java.time
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
Now in maintenance mode, the Joda-Time project also 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.
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time.
LocalDateTime
Your input string lacks any indication of offset-from-UTC or time zone. So we must parse as a LocalDateTime. A LocalDateTime has no offset or time zone, so it does not represent a moment on the timeline. Like saying "Christmas starts at midnight on December 25", that only has meaning (only becomes a point on the timeline) when you apply it to a particular time zone somewhere on the planet.
String input = …
DateTimeFormatter f = DateTimeFormatter.forPattern( "dd/MM/uuuu hh:mm:ss" );
LocalDateTime ldt = LocalDateTime.parse( input , f );
ZonedDateTime
If you know the context and can assume the intended offset or time zone, you can create an OffsetDateTime or ZonedDateTime respectively.
Use proper time zone names, named in the format of continent/region. By MST perhaps you meant the America/Denver time zone used in much of the Rocky Mountains parts of the United States, or America/Edmonton used in parts of Canada.
Never use the 3-4 letter abbreviations such as MST. These abbreviations are not true time zones, are not standardized, and are not even unique(!).
ZoneId zoneId = ZoneId.of( "America/Denver" ) ;
ZonedDateTime zdt = ldt.atZone( zoneId ) ;
Converting
I suggest avoiding the notoriously troublesome java.util.Date class. But if you must do so , you may convert to/from java.time types. To interoperate with other code or libraries, convert using new methods added to the old classes. In this case, use a Instant object extracted from the OffsetDateTime or ZonedDatetime and pass to java.util.Date.from.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() ) ;
Going the other direction, use another new method added to the old class, java.util.Instant::toInstant.
Instant instant = utilDate.toInstant();
ZonedDateTime zdt = instant.atZone( zoneId ) ;

Unparseable date: "1/29/2014 11:45:00 AM" - Android

I have a problem with parsing the following date from string: "1/29/2014 11:45:00 AM"
I do it the following way:
String source = "1/29/2014 11:45:00 AM";
Date startDate;
String sdfPattern = "MM/dd/yyyy hh:mm:ss aa";
SimpleDateFormat sdf = new SimpleDateFormat(sdfPattern, Locale.getDefault());
sdf.setTimeZone(TimeZone.getTimeZone("Europe/London"));
this.startDate = sdf.parse(source);
Interestingly, this works fine in a java project, but not in android. The error message I get:
01-15 15:36:46.950: W/System.err(2713): java.text.ParseException: Unparseable date: "1/29/2014 11:45:00 AM" (at offset 19)
Can anybody tell me what I am doing wrong?
Your format string specifies that you'll provide a two-digit month, but you're only providing "1".
I suspect you want:
String sdfPattern = "M/d/yyyy hh:mm:ss aa";
Additionally, the "AM/PM" designator is locale-sensitive (as are the date and time separators) . If you know that it will always use English, you should say so:
SimpleDateFormat sdf = new SimpleDateFormat(sdfPattern, Locale.US);
Unless the data is actually entered by the user (or being formatted for the user) you should avoid Locale.getDefault().
Your default locale may not match the AM/PM marker in the input String causing the exception. Try using
SimpleDateFormat sdf = new SimpleDateFormat(sdfPattern, Locale.ENGLISH);
java.time
The Question and other Answers use the troublesome old legacy date-time classes bundled with the earliest versions of Java. Now supplanted by the java.time classes.
ISO 8601
By the way, use the ISO 8601 formats when generating Strings to represent date-time values for exchange with other software. Your format is ambiguous and trickier to parse, unlike the standard formats.
DateTimeFormatter
The codes defining a formatting pattern in java.time.DateTimeFormatter are similar to the outmoded SimpleDateFormat but not exactly. So read the doc carefully.
String input = "1/29/2014 11:45:00 AM";
Locale locale = Locale.ENGLISH; // For translating the “AM” & “PM”.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "M/d/uuuu hh:mm:ss a" ).withLocale( locale );
LocalDateTime
Your input lacks any indication of an offset-from-UTC or a time zone. So we parse as a LocalDateTime object.
LocalDateTime ldt = LocalDateTime.parse ( input , f );
ldt.toString(): 2014-01-29T11:45
A LocalDateTime object purposely lacks any offset-from-UTC or time zone. That means it does not represent a moment on the timeline, only a rough idea about possible moments. You must assign an offset or time zone to give it meaning.
OffsetDateTime
If the context of your suggestions indicates this input was meant to be in UTC, apply the constant ZoneOffset.UTC to get an OffsetDateTime.
OffsetDateTime odt = ldt.atOffset ( ZoneOffset.UTC );
odt.toString(): 2014-01-29T11:45Z
ZonedDateTime
On the other hand, if the context indicates a specific time zone, apply a ZoneId to get a ZonedDateTime. The Questions seems to indicate that the Europe/London time zone is intended. Be aware that this time zone is not the same as UTC.
ZoneId z = ZoneId.of ( "Europe/London" );
ZonedDateTime zdt = ldt.atZone ( z );
zdt.toString(): 2014-01-29T11:45-05:00[America/Montreal]
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. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Convert String to Util Date using simpleDateFormat not working

I'm having a String having date in it, I need hh:mm:ss to be added to the date, but when i use dateFormat it gives me ParseException. Here is the code:
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String startDate = "2013-09-25";
Date frmDate;
frmDate = sdff.parse(startDate);
System.out.println("from date = " + frmDate);
I get parse exception for the abv code. But if i remove the hh:mm:ss from the Date format it works fine and the output will be from date = Wed Sep 25 00:00:00 IST 2013.
But I need output like from date = 2013-09-25 00:00:00
Please help me.
Thanks in advance.
You'll need 2 SimpleDateFormat objects for that. One to parse your current date string and the other to format that parsed date to your desired format.
// This is to parse your current date string
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String startDate = "2013-09-25";
Date frmDate = sdf.parse(startDate); // Handle the ParseException here
// This is to format the your current date to the desired format
DateFormat sdff = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String frmDateStr = sdff.format(frmDate);
Edit:-
Date doesn't have a format as such. You can only get a String representation of it using the SDF. Here an excerpt from the docs
A thin wrapper around a millisecond value that allows JDBC to identify
this as an SQL DATE value. A milliseconds value represents the number
of milliseconds that have passed since January 1, 1970 00:00:00.000
GMT.
And regarding your problem to insert it in the DB, java Date can be as such persisted in the DB date format. You don't need to do any formatting. Only while fetching the date back from DB, you can use the to_char() method to format it.
parse() is used to convert String to Date.It requires the formats to be matched otherwise you will get exception.
format() is used convert the date into date/time string.
Accroding to your requirement you need to use above two methods.
DateFormat parser = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String startDate = "2013-09-25";
Date parsedDate = parser.parse(startDate);
String formattedDate = dateFormatter.format(parsedDate);//this will give your expected output
tl;dr
LocalDate.parse( "2013-09-25" ) // Parse the string as a date-only object lacking time-of-day and lacking time zone.
.atStartOfDay( // Let java.time determine the first moment of the day. Not always 00:00:00 because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "America/Montreal" ) // Specify a time zone using legitimate `continent/region` name rather than 3-4 letter pseudo-zones.
) // Returns a `ZonedDateTime` object.
.toString() // Generate a string in standard ISO 8601 format, wisely extended from the standard by appending the name of the time zone in square brackets.
2013-09-25T00:00-04:00[America/Montreal]
To generate your string, pass a DateTimeFormatter.
LocalDate.parse( "2013-09-25" ) // Parse the string as a date-only object lacking time-of-day and lacking time zone.
.atStartOfDay( // Let java.time determine the first moment of the day. Not always 00:00:00 because of anomalies such as Daylight Saving Time (DST).
ZoneId.of( "America/Montreal" ) // Specify a time zone using legitimate `continent/region` name rather than 3-4 letter pseudo-zones.
) // Returns a `ZonedDateTime` object.
.format( // Generate a string representing the value of this `ZonedDateTime` object.
DateTimeFormatter.ISO_LOCAL_DATE_TIME // Formatter that omits zone/offset.
).replace( "T" , " " ) // Replace the standard’s required 'T' in the middle with your desired SPACE character.
2013-09-25 00:00:00
Details
Your formatting pattern must match your input, as pointed out by others. One formatter is needed for parsing strings, another for generating strings.
Also, you are using outmoded classes.
java.time
The modern approach uses the java.time classes that supplanted the troublesome old legacy date-time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
You can parse a string to produce a LocalDate. The standard ISO 8601 formats are used in java.time by default. So no need to specify a formatting pattern.
LocalDate ld = LocalDate.parse( "2013-09-25" ) ;
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" ) ;
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( 2013 , 9 , 25 ) ; // Years use sane direct numbering (2013 means year 2013). 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( 2013 , Month.SEPTEMBER , 25 ) ;
Formats
If you want to get the first moment of the day for that date, apply a time zone. As mentioned above, a date and time-of-day require the context of a time zone or offset-from-UTC to represent a specific moment on the timeline.
Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00. Let java.time determine the first moment of the day.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ld.atZone( z ) ;
If you want output in the format shown in your Question, you can define your own format. I caution you against omitting the time zone or offset info from the resulting string unless you are absolutely certain the user can discern its meaning from the greater context.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" ) ;
String output = zdt.format( f ) ;
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.
It is because your string is yyyy-MM-dd, but the date format u defined is yyyy-MM-dd hh:mm:ss.
If you change your string startDate to yyyy-MM-dd hh:mm:ss it should work
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sdf.parse(sdf.format(new Date()));
This will return a Date type
The issue is '2013-09-25' date cannot be parsed to 'yyyy-MM-dd hh:mm:ss' date format. First you need to parse following date into its matching pattern which is 'yyyy-MM-dd'.
Once it is parsed to its correct pattern you can provide the date pattern you prefer which is 'yyyy-MM-dd hh:mm:ss'.
Now you can format the Date and it will output the date as you preferred.
SimpleDateFormat can be used to achieve this outcome.
Try this code.
String startDate = "2013-09-25";
DateFormat existingPattern = new SimpleDateFormat("yyyy-MM-dd");
DateFormat newPattern = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = existingPattern.parse(startDate);
String formattedDate = newPattern.format(date);
System.out.println(formattedDate); //outputs: 2013-09-25 00:00:00

Converting string to date with timezone

I have a string in the pattern yyyy-MM-dd hh:mm a
and i can get the time zone object separately in which the above string represents the date.
I want to convert this to the below format.
yyyy-MM-dd HH:mm:ss Z
How can i do this?
You can use SimpleDateFormat with yyyy-MM-dd HH:mm:ss and explicitly set the TimeZone:
public static Date getSomeDate(final String str, final TimeZone tz)
throws ParseException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm a");
sdf.setTimeZone(tz);
return sdf.parse(str);
}
/**
* #param args
* #throws IOException
* #throws InterruptedException
* #throws ParseException
*/
public static void main(final String[] args) throws ParseException {
final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
System.out.println(sdf.format(getSomeDate(
"2010-11-17 01:12 pm", TimeZone.getTimeZone("Europe/Berlin"))));
System.out.println(sdf.format(getSomeDate(
"2010-11-17 01:12 pm", TimeZone.getTimeZone("America/Chicago"))));
}
Prints out:
2010-11-17 13:12:00 +0100
2010-11-17 20:12:00 +0100
Update 2010-12-01:
If you want to explicitly printout a special TimeZone, set it in the SimpleDateFormat:
sdf.setTimeZone(TimeZone .getTimeZone("IST"));
System.out.println(sdf.format(getSomeDate(
"2010-11-17 01:12 pm", TimeZone.getTimeZone("IST"))));
Which prints 2010-11-17 13:12:00 +0530
tl;dr
LocalDateTime.parse( // Parse string as value without time zone and without offset-from-UTC.
"2017-01-23 12:34 PM" ,
DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" )
) // Returns a `LocalDateTime` object.
.atZone( ZoneId.of( "America/Montreal" ) ) // Assign time zone, to determine a moment. Returns a `ZonedDateTime` object.
.toInstant() // Adjusts from zone to UTC.
.toString() // Generate string: 2017-01-23T17:34:00Z
.replace( "T" , " " ) // Substitute SPACE for 'T' in middle.
.replace( "Z" , " Z" ) // Insert SPACE before 'Z'.
Avoid legacy date-time classes
The other Answers use the troublesome old date-time classes (Date, Calendar, etc.), now legacy, supplanted by the java.time classes.
LocalDateTime
I have a string in the pattern yyyy-MM-dd hh:mm a
Such an input string lacks any indication of offset-from-UTC or time zone. So we parse as a LocalDateTime.
Define a formatting pattern to match your input with a DateTimeFormatter object.
String input = "2017-01-23 12:34 PM" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd hh:mm a" );
LocalDateTime ldt = LocalDateTime.parse( input , f );
ldt.toString(): 2017-01-23T12:34
Note that a LocalDateTime is not a specific moment, only a vague idea about a range of possible moments. For example, a few minutes after midnight in Paris France is still “yesterday” in Montréal Canada. So without the context of a time zone such as Europe/Paris or America/Montreal, just saying “a few minutes after midnight” has no meaning.
ZoneId
and i can get the time zone object separately in which the above string represents the date.
A time zone is represented by the ZoneId class.
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" );
ZonedDateTime
Apply the ZoneId to get a ZonedDateTime which is indeed a point on the timeline, a specific moment in history.
ZonedDateTime zdt = ldt.atZone( z );
zdt.toString(): 2017-01-23T12:34-05:00[America/Montreal]
Instant
I want to convert this to the below format. yyyy-MM-dd HH:mm:ss Z
First, know that a Z literal character is short for Zulu and means UTC. In other words, an offset-from-UTC of zero hours, +00:00.
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 extract a Instant object from a ZonedDateTime.
Instant instant = zdt.toInstant(); // Extracting the same moment but in UTC.
To generate a string in standard ISO 8601 format, such as 2017-01-22T18:21:13.354Z, call toString. The standard format has no spaces, uses a T to separate the year-month-date from the hour-minute-second, and appends the Z canonically for an offset of zero.
String output = instant.toString();
instant.toString(): 2017-01-23T17:34:00Z
I strongly suggest using the standard formats whenever possible. If you insist on using spaces as in your stated desired format, either define your own formatting pattern in a DateTimeFormatter object or just do a string manipulation on the output of Instant::toString.
String output = instant.toString()
.replace( "T" , " " ) // Substitute SPACE for T.
.replace( "Z" , " Z" ); // Insert SPACE before Z.
output: 2017-01-23 17:34:00 Z
Try this code live at IdeOne.com.
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.
Use SimpleDateFormat
String string1 = "2009-10-10 12:12:12 ";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);
Create a new instance of SimpleDateFormat using your date pattern. Afterwards you can call it's parse method to convert date strings to a java.util.Date object.
Undoubtedly, the format which is generally used will be of a form 2014-10-05T15:23:01Z (TZ)
For that one has to use this code
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
String dateInString = "2014-10-05T15:23:01Z";
try {
Date date = formatter.parse(dateInString.replaceAll("Z$", "+0000"));
System.out.println(date);
} catch (ParseException e) {
e.printStackTrace();
}
Its output will be Sun Oct 05 20:53:01 IST 2014
However, I am not sure why we had to replaceAll "Z" if you do not add replaceAll the program will fail.
Please try this for the format "yyyy-MM-dd HH:mm:ss Z",
Eg: "2020-12-11 22:59:59 GMT", you can use different time zones like PST, GMT, etc.

Categories

Resources