Convert string to appropriate date with timezone java - java

I am Having Date with it's timezone, I want to convert it to another Timezone, E.g. I have Date '3/15/2013 3:01:53 PM' which is in TimeZone 'GMT-06:00'. I want to convert this in 'GMT-05:00' timezone. I have search lot, and I am confuse about How actually Date is working. How to Apply timezone to date. I have try with SimpleDateFormat, Calender and also with offset.
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aaa XXX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
Date dt = null;
try {
dt = df.parse("3/15/2013 3:01:53 PM -06:00");
} catch (ParseException e) {
e.printStackTrace();
}
String newDateString = df.format(dt);
System.out.println(newDateString);
It returns output
03/15/2013 09:01:53 AM Z.
I guess it should be
03/15/2013 09:01:53 PM Z, because time in 'GMT-06:00' timezone, so it should be HH+6 to get time in GMT. I want Date in "yyyy-MM-dd HH:mm:ss" format where HH is in 24 hour.Please Help me with example. Thanks in advance.
EDIT :
I am converting the string into date using SimpleDateFormat
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss aaa");
Date dt = null;
try {
dt = df.parse("3/15/2013 3:01:53 PM");
} catch (ParseException e) {
e.printStackTrace();
}
Now, as you say, I specify to Calendar that my date is in 'GMT-06:00' timezone and set my date,
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("GMT-6"));
cal.setTime(dt);
Now, I am telling calendar that I want date in 'GMT'
cal.setTimeZone (TimeZone.getTimeZone("GMT"));
System.out.println(cal.getTime());
OutPut:
Fri Mar 15 03:01:53 CDT 2013
Please know me if i am going wrong.

You need TWO format objects, one for parsing and another one for printing because you use two different timezones, see here:
// h instead of H because of AM/PM-format
DateFormat parseFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
Date dt = null;
try {
dt = parseFormat.parse("3/15/2013 3:01:53 PM -06:00");
}catch (ParseException e) {
e.printStackTrace();
}
DateFormat printFormat = new SimpleDateFormat("M/dd/yyyy hh:mm:ss aaa XXX");
printFormat.setTimeZone(TimeZone.getTimeZone("GMT-05"));
String newDateString = printFormat.format(dt);
System.out.println(newDateString);
Output: 3/15/2013 04:01:53 PM -05:00
If you want HH:mm:ss (24-hour-format) then you just replace
hh:mm:ss aaa
by
HH:mm:ss
in printFormat-pattern.
Comment on other aspects of question:
A java.util.Date has no internal timezone and always refers to UTC by spec. You cannot change it inside this object. A timezone conversion is possible for the formatted string, however as demonstrated in my code example (you wanted to convert to zone GMT-05).
The question then switches to the new requirement to print the Date-object in ISO-format using UTC timezone (symbol Z). This can be done in formatting by replacing the pattern with "yyyy-MM-dd'T'HH:mm:ssXXX" and explicitly setting the timezone of printFormat to GMT+00. You should clarify what you really want as formatted output.
About java.util.GregorianCalendar: Setting the timezone here is changing the calendar-object in a programmatical way, so it affects method calls like calendar.get(Calendar.HOUR_OF_DAY). This has nothing to do with formatting however!

tl;dr
OffsetDateTime.parse(
"3/15/2013 3:01:53 PM -06:00" ,
DateTimeFormatter.ofPattern( "M/d/yyyy H:mm:ss a XXX" )
).withOffsetSameInstant(
ZoneOffset.of( -5 , 0 )
)
2013-03-15T15:01:53-06:00
java.time
The Answer by Hochschild is correct but uses outdated classes. The troublesome old date-time classes bundled with the earliest versions of Java have been supplanted by the modern java.time classes.
Parse your input string as a OffsetDateTime as it contains an offset-from-UTC but not a time zone.
String input = "3/15/2013 3:01:53 PM -06:00";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/yyyy h:mm:ss a XXX" );
OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2013-03-15T15:01:53-06:00
Tip: Save yourself some hassle and use the ISO 8601 formats when exchanging date-time data as text. The java.time classes use these standard formats by default when parsing/generating strings.
Apparently you want to see the same moment as viewed by the people elsewhere using a different offset-from-UTC.
ZoneOffset offset = ZoneOffset.of( -5 , 0 ) ;
OffsetDateTime odt2 = odt.withOffsetSameInstant( offset ) ;
We see the offset changes from 6 to 5, and the hour-of-day changes accordingly from 15 to 16. Same simultaneous moment, different wall-clock time.
odt2.toString(): 2013-03-15T16:01:53-05:00
Generating strings
I want Date in "yyyy-MM-dd HH:mm:ss" format where HH is in 24 hour.
I suggest you always include some indication of the offset or zoneunless your are absolutely certain the user understands from the greater context.
Your format is nearly in standard ISO 8601 format. You could define your own formatting pattern, but I would just do string manipulation to replace the T in the middle with a SPACE.
String output = odt2.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " ) ;
2013-03-15 16:01:53
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.

Related

Joda Time parse a date with timezone and retain that timezone

I want to parse a date, which was created with a specific timezone, convert it to a format and return it. The conversion works but the timezone offset is always set to +0000 with the time difference being added/subtracted as necessary. How can I get it to format and keep the offset correct?
I expect this: 2012-11-30T12:08:56.23+07:00
But get this: 2012-11-30T05:08:56.23+00:00
Implementation:
public static final String ISO_8601_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSZZ";
public static String formatDateToISO8601Standard(Date date) {
DateTime dateTime = new DateTime(date);
DateTimeFormatter df = DateTimeFormat.forPattern(ISO_8601_DATE_FORMAT);
return dateTime.toString(df);
}
Test class:
private static final String DATE_WITH_TIMEZONE = "30 11 2012 12:08:56.235 +0700";
private static final String EXPECTED_DATE_WITH_TIMEZONE = "2012-11-30T12:08:56.23+07:00";
#Test public void testFormattingDateWithSpecificTimezone() throws Exception {
String result = JodaDateUtil.formatDateToISO8601Standard(createDate(DATE_WITH_TIMEZONE));
assertEquals("The date was not converted correctly", EXPECTED_DATE_WITH_TIMEZONE, result); }
private Date createDate(String dateToParse) throws ParseException {
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.parseDateTime(dateToParse);
Date date = temp.toDate();
return date; }
Basically, once you parse the date string [in your createDate() method] you've lost the original zone. Joda-Time will allow you to format the date using any zone, but you'll need to retain the original zone.
In your createDate() method, the DateTimeFormatter "df" can return the zone that was on the string. You'll need to use the withOffsetParsed() method. Then, when you have your DateTime, call getZone(). If you save this zone somewhere or somehow pass it to your formatting routine, then you can use it there by creating a DateTimeFormatter "withZone" and specifying that zone as the one you want on the format.
As a demo, here's some sample code in a single method. Hopefully, it'll help change your code the way you want it to run.
public static void testDate()
{
DateTimeFormatter df = DateTimeFormat.forPattern("dd MM yyyy HH:mm:ss.SSS Z");
DateTime temp = df.withOffsetParsed().parseDateTime("30 11 2012 12:08:56.235 +0700");
DateTimeZone theZone = temp.getZone();
Date date = temp.toDate();
DateTime dateTime = new DateTime(date);
DateTimeFormatter df2 = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSZZ");
DateTimeFormatter df3 = df2.withZone(theZone);
System.out.println(dateTime.toString(df2));
System.out.println(dateTime.toString(df3));
}
tl;dr
OffsetDateTime.parse (
"30 11 2012 12:08:56.235 +0700" ,
DateTimeFormatter.ofPattern ( "dd MM uuuu HH:mm:ss.SSS X" , Locale.US )
).toString()
2012-11-30T12:08:56.235+07:00
Details
The accepted Answer is correct. As soon as you convert to a java.util.Date object, you lose time zone information. This is complicated by the fact that java.util.Date::toString confusingly applies a current default time zone when generating the String.
Avoid using these old date-time classes like java.util.Date. They are poorly-designed, confusing, and troublesome. Now legacy, supplanted by the java.time project. So too is the Joda-Time project now supplanted by the java.time classes.
java.time
Parse that input string as a OffsetDateTime object as it includes an offset-from-UTC but lacks a time zone. Call DateTimeFormatter.ofPattern to specify a custom format matching your input string. Pass that formatter object to OffsetDateTime.parse.
String input = "30 11 2012 12:08:56.235 +0700" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "dd MM uuuu HH:mm:ss.SSS X" , Locale.US );
OffsetDateTime odt = OffsetDateTime.parse ( input , f );
odt:toString(): 2012-11-30T12:08:56.235+07:00
To see the same moment in UTC, extract an 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 = odt.toInstant();
instant.toString(): 2012-11-30T05:08:56.235Z
You can apply any time zone through which you want to view the same moment, the same point on the timeline.
ZonedDateTime zdtKolkata = odt.toInstant ().atZone ( ZoneId.of ( "Asia/Kolkata" ) );
zdtKolkata.toString(): 2012-11-30T10:38:56.235+05:30[Asia/Kolkata]
No need to mix in the old date-time classes at all. Stick with java.time. If you must use some old code not yet updated to java.time types, look to new methods added to the old classes to convert to/from java.time.
The equivalent of java.util.Date is Instant, both being a count-since-epoch of 1970-01-01T00:00:00Z in UTC. But beware of data-loss as the java.time classes support nanosecond resolution but the old classes are limited to milliseconds.
java.util.Date utilDate = java.util.Date.from( instant );
Live code
See live working code in 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, & 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. 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.
Try this.
ISODateTimeFormat.dateTimeParser().parseDateTime(dateString),
then convert that to the format you desire.
Use the format
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSZZ")

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

I need to convert a String containing date into an date object. The String will be of the format "yyyy-mm-dd HH:mm:ss.SSSSSS" and I want the same format in an date object.
For instance I have a string "2012-07-10 14:58:00.000000", and I need the resultant date object to be of the same format.
I have tried the below methods but, the resultant is not as expected.
java.util.Date temp = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");
DateFormat dateFormat = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");
Date thisDate = dateFormat.parse("2012-07-10 14:58:00.000000");
The result is "Tue Jan 10 14:58:00 EST 2012". Please let me know where I am going wrong.
Thanks,
Yeshwanth Kota
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS").parse("2012-07-10 14:58:00.000000");
The mm is minutes you want MM
CODE
public class Test {
public static void main(String[] args) throws ParseException {
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS")
.parse("2012-07-10 14:58:00.000000");
System.out.println(temp);
}
}
Prints:
Tue Jul 10 14:58:00 EDT 2012
For future reference:
yyyy => 4 digit year
MM => 2 digit month (you must type MM in ALL CAPS)
dd => 2 digit "day of the month"
HH => 2-digit "hour in day" (0 to 23)
mm => 2-digit minute (you must type mm in lowercase)
ss => 2-digit seconds
SSS => milliseconds
So "yyyy-MM-dd HH:mm:ss" returns "2018-01-05 09:49:32"
But "MMM dd, yyyy hh:mm a" returns "Jan 05, 2018 09:49 am"
The so-called examples at https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html show only output. They do not tell you what formats to use!
tl;dr
LocalDateTime.parse(
"2012-07-10 14:58:00.000000".replace( " " , "T" )
)
Microseconds do not fit
You are attempting to squeeze a value with microseconds (six decimal digits) into a data type capable only of milliseconds resolution (three decimal digits). That is impossible.
Instead, use a data type with fine enough resolution. The java.time classes use nanosecond resolution (nine decimal digits).
Unzoned input does not fit a zoned type
You are attempting to put a value lacking any offset-from-UTC or time zone into a data type (Date) that only represents values in UTC. So you are adding information (UTC offset) not intended by the input.
Use an appropriate data type instead. Specifically, java.time.LocalDateTime.
Case-sensitive
Other Answers and Comments correctly explain that the formatting pattern codes are case-sensitive. So MM and mm have different effects.
Avoid legacy classes
The troublesome old date-time classes bundled with the earliest versions of Java are now legacy, supplanted by the java.time classes built into Java 8 and later.
ISO 8601
Your input strings nearly comply with the ISO 8601 standard formats. Replace the SPACE in the middle with a T to comply fully.
The java.time classes use the standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Date-time objects have no "format"
and I need the resultant date object to be of the same format.
No, date-time objects do not have a "format". Do not conflate date-time objects with mere strings. Strings are inputs and outputs of the objects. The objects maintain their own internal representions of the date-time info, the details of which are irrelevant to us as calling programmers.
java.time
Your input lacks any indicator of offset-from-UTC or troublesome me zone. So we parse as a LocalDateTime objects which lacks those concepts.
String input = "2012-07-10 14:58:00.000000".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input ) ;
Generating strings
To generate a String representing the value of your LocalDateTime:
Call toString to get a String in standard ISO 8601 format.
Use DateTimeFormatter for producing strings in either custom formats or automatically-localized formats.
Search Stack Overflow for more info as these topics have been covered many many times already.
ZonedDateTime
A LocalDateTime does not represent an exact point on the timeline.
To determine an actual moment, assign a time zone. For example noon in Kolkata India comes much earlier than noon in Paris France. Noon without a time zone could be happening at any point over a range of about 26-27 hours.
ZoneId z = ZoneId.of( "Asia/Kolkata" ) ;
ZonedDateTime zdt = ldt.atZone( 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.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
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. Hibernate 5 & JPA 2.2 support java.time.
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 brought 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 (26+) bundle implementations of the java.time classes.
For earlier Android (<26), the process of API desugaring brings a subset of the java.time functionality not originally built into Android.
If the desugaring does not offer what you need, the ThreeTenABP project adapts ThreeTen-Backport (mentioned above) to Android. See How to use ThreeTenABP….
Your not applying Date formator. rather you are just parsing the date. to get output in this format
yyyy-MM-dd HH:mm:ss.SSSSSS
we have to use format() method here is full example:-
Here is full example:-
it will take Date in this format yyyy-MM-dd HH:mm:ss.SSSSSS
and as result we will get output as same as this format yyyy-MM-dd HH:mm:ss.SSSSSS
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
//TODO OutPut should LIKE in this format yyyy-MM-dd HH:mm:ss.SSSSSS.
public class TestDateExample {
public static void main(String args[]) throws ParseException {
SimpleDateFormat changeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSSSSS");
java.util.Date temp = changeFormat.parse("2012-07-10 14:58:00.000000");
Date thisDate = changeFormat.parse("2012-07-10 14:58:00.000000");
System.out.println(thisDate);
System.out.println("----------------------------");
System.out.println("After applying formating :");
String strDateOutput = changeFormat.format(temp);
System.out.println(strDateOutput);
}
}
its work for me
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf.format(new Date));

How can I parse this Date in Java?

I want to parse a date into my format like 02:09 AM 25/09/2012 but I can't. I used this code.
SimpleDateFormat sdf1 = new SimpleDateFormat("MMMM, DD yyyy HH:mm:ss Z");
//September, 25 2012 02:09:42 +0000
Date date = sdf1.parse(String.valueOf(PUNCH_TIME));
SimpleDateFormat sdf2 = new SimpleDateFormat("HH':'mm a 'on' DD'/'MMMM'/'yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("MM");
String timeformat=sdf2.format(date);
txtHomePunchStatus.setText("You have Punched In at "+timeformat);
and I got You have punched IN at 7:52 AM on 25/01/2012.
You probably have issues with the time zone. The input string September, 25 2012 02:09:42 +0000 is a timestamp in UTC (offset +0000). When you format your date in the desired format, you're not specifying a time zone, so the SimpleDateFormat object is going to show your date in your local time zone, which is probably not UTC.
What you can do is set the time zone on the SimpleDateFormat object that you use to format the date. For example:
DateFormat df1 = new SimpleDateFormat("MMMM, dd yyyy HH:mm:ss Z");
Date date = df1.parse(PUNCH_TIME);
DateFormat df2 = new SimpleDateFormat("HH:mm a 'on' dd/MM/yyyy");
df2.setTimeZone(TimeZone.getTimeZone("UTC"));
String result = df2.format(date);
System.out.println(result);
Note: You must use dd and not DD for the days; DD means day number of the year, dd means day number in the month (see the API documentation of SimpleDateFormat).
p.s.: Your usage of the words "parse" and "format" is confusing. Parsing means: converting from a string to a Date object, and formatting means the opposite: converting from a Date object to a string.
First off you have a double declaration of sdf2. Then, you need to use hh and mm for hours and minutes. Read the documentation: SimpleDateFormat Like in this example:
SimpleDateFormat sdf1 = new SimpleDateFormat("MMMM, DD yyyy HH:mm:ss Z");
//September, 25 2012 02:09:42 +0000
Date date = null;
try {
date = sdf1.parse(String.valueOf(PUNCH_TIME));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SimpleDateFormat sdf2 = new SimpleDateFormat("hh:mm a 'on' DD/MM/yyyy");
String timeformat=sdf2.format(date);
tl;dr
OffsetDateTime.parse(
"September, 25 2012 02:09:42 +0000" ,
DateTimeFormatter.ofPattern( "MMMM, d uuuu HH:mm:ss Z" , Locale.US )
).format(
DateTimeFormatter.ofPattern( "hh:mm a 'on' dd/MM/uuuu" , Locale.US )
)
02:09 AM on 25/09/2012
Avoid legacy date-time classes
The other Answers are now outmoded, using troublesome old date-time classes that are now legacy. The old classes are supplanted by the java.time classes. For earlier Android, see the last bullets below.
java.time
Define a formatting pattern to match your input string.
String input = "September, 25 2012 02:09:42 +0000" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "MMMM, d uuuu HH:mm:ss Z" , Locale.US ) ; // Specify a locale for the human language by which to parse the name of the month.
Parse as an OffsetDateTime given that your input specifies an offset-from-UTC but not a full time zone.
OffsetDateTime odt = OffsetDateTime odt = OffsetDateTime.parse( input , f );
odt.toString(): 2012-09-25T02:09:42Z
To generate a string in an alternate format, define a DateTimeFormatter with a custom formatting pattern. Pay attention to the uppercase/lowercase of your formatting code characters, and study closely the documentation. Note that colons, spaces, and slashes are known by the formatter, so no need to escape those characters with the single-quote marks.
DateTimeFormatter fOutput = DateTimeFormatter.ofPattern( "hh:mm a 'on' dd/MM/uuuu" , Locale.US ) ;
String output = odt.format( fOutput) ;
02:09 AM on 25/09/2012
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.

Convert java.sql.Timestamp to java.sql.Timestamp in another timezone

I am in need to manipulate on java.sql.Timestamp.
Input to the function is:
Formatted DateTime in java.sql.Timestamp
[Possible date formats are: MM/dd/yyyy hh:mm:ss aa, MM/dd/yyyy hh:mm:ss, MM/dd/yyyy hh:mm aa, MM/dd/yyyy HH:mm, MM/dd/yy hh:mm aa, MM/dd/yy HH:mm, MM/dd/yyyy, and some others]
Required Output:
java.sql.Timestamp in another Timezone the same formatted DateTime as input
So basically I need to change timezone of the DateTime in java.sql.Timestamp
I have seen other posts, which mention to use JODA, but I can't use it due to some restrictions.
I have tried
- to convert java.sql.Timestamp to java.date.Calendar,
- then change the timezone,
- then convert to it to date
- format date to the same formatted datetime
See the code below:
Timestamp ts = "2012-06-20 18:22:42.0"; // I get this type of value from another function
Calendar cal = Calendar.getInstance();
cal.setTime(ts);
cal.add(Calendar.HOUR, -8);
String string = cal.getTime().toString(); // return value is in " DAY MMM dd hh:mm:ss PDT yyyy " format i.e. Wed Jun 20 10:22:42 PDT 2012
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss"); // This could be any format required
Date date;
try {
date = formatter.parse(string); // I am getting exception here on parsing
} catch (ParseException e1) {
e1.printStackTrace();
}
Can anyone tell me what is wrong here, or is there any other way to manipulate on Timezone for java.sql.Timestamp ?
Thanks.
You are misunderstanding and abusing these classes.
Timestamp & Date have no time zone but UTC
manipulate on Timezone for java.sql.Timestamp
A java.sql.Timestamp is always a moment in UTC. No other time zone is involved, only UTC. Ditto for java.util.Date – always in UTC, no other time zone involved.
So your Question, as quoted above, does not make sense.
Timestamp & Date have no “format”
Neither Timestamp nor Date have a “format”. They use their own internally defined way to track the date-time. They are not strings, so they have no format. You can generate a String to represent their value in a particular format, but such a String is distinct and separate from the generating object.
java.time
You are using troublesome old date-time classes that wore supplanted years ago by the java.time classes.
Both Timestamp and Date are 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).
Your input is
String input = "2012-06-20 18:22:42.0" ;
That input is nearly compliant with standard ISO 8601 format. To comply fully, replace the SPACE in the middle with a T.
String input = "2012-06-20 18:22:42.0".replace( " " , "T" ) ;
Parse as a LocalDateTime because it lacks an indicator of offset-from-UTC or time zone.
LocalDateTime ldt = LocalDateTime.parse( input ) ;
A LocalDateTime, like your input string, does not represent a moment, is not a point on the timeline. Without the context of a time zone or offset-from-UTC, it has no real meaning. It represents only potential moments along a range of about 26-27 hours.
If you know the intended time zone, apply it to get a ZonedDateTime object.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = ldt.atZone( z ) ;
As for the other formats you mentioned, your Question is not at all clear. Search Stack Overflow for DateTimeFormatter class to see many examples and discussions of generating/parsing strings with the java.time classes. But first, get clear on the crucial concept that strings are not the date-time objects, and the date-time objects are not strings.
Database
If you were using java.sql.Timestamp to exchange data with a database, no need for that class anymore. As of JDBC 4.2 and later, you can directly exchange java.time objects with your database.
myPreparedStatement.setObject( … , instant ) ;
…and…
Instant instant = myResultSet.getObject( … , Instant.class ) ;
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.
Think of Timestamp as being a fixed point in time, disconnected from where on earth you happen to be looking at a clock.
If you want to display what's on the calendar/clock for a person at that instant in a particular time zone, you can set a calendar to that time zone and then associate your SimpleDateFormat to that calendar.
For example:
public void testFormat() throws Exception {
Calendar pacific = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
Calendar atlantic = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Timestamp ts = new Timestamp(System.currentTimeMillis());
sdf.setCalendar(pacific);
System.out.println(sdf.format(ts));
sdf.setCalendar(atlantic);
System.out.println(sdf.format(ts));
}
My output was:
2012-06-25 20:27:12.506
2012-06-25 23:27:12.506
I got it solved, I am putting code for reference.
Timestamp ts = "2012-06-20 18:22:42.0"; // input date in Timestamp format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Calendar cal = Calendar.getInstance();
cal.setTime(ts)
cal.add(Calendar.HOUR,-7); // Time different between UTC and PDT is -7 hours
String convertedCal = dateFormat.format(cal.getTime()); // This String is converted datetime
/* Now convert String formatted DateTime to Timestamp*/
SimpleDateFormat formatFrom = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
try {
Date date = formatFrom.parse(convertedCal);
Timestamp finalTS = new Timestamp(date.getTime()); // Final value in Timestamp: 2012-06-20 11:22:42.0
} catch (Exception e) {
e.printStackTrace();
}
Couldn't you simply:
Get original time in milliseconds
Convert timezone difference to milliseconds
Add or subtract the difference from the original time.
Create a new timestamp using the new time in milliseconds
you miss one argumment in formatter.parse
http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#parse(java.lang.String,%20java.text.ParsePosition)

SimpleDateFormat "Unparseable date" Exception

I am trying to parse datetime string with SimpleDateFormat.parse() but I keep receiving Unparseable date exceptions.
Here is the date format I am trying to parse: 2011-10-06T12:00:00-08:00
Here is the code I am using:
try {
String dateStr = "2011-10-06T12:00:00-08:00";
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
SimpleDateFormat dateFormatter = new SimpleDateFormat("MMM d, yyyy");
Date date = dateParser.parse(dateStr);
System.out.println(dateFormatter.format(date));
} catch(Exception e) {
System.out.println(e.getMessage());
}
Which returns this error: java.text.ParseException: Unparseable date: "2011-10-06T12:00:00-08:00"
As far as I know this is the correct way to use the SimpleDateFormat class but I'm not fluent in Java so I could be mistaken. Any one know what my issue is?
The timezone should be GMT-08:00 or -0800 (as Madcore Tom said). See Java docs.
In Java 7 you can use "yyyy-MM-dd'T'HH:mm:ssX"
I believe that SimpleDateFormat will not parse timezones with a colon in them (-08:00). It should be able to parse the date 2011-10-06T12:00:00-0800.
Some simple string manipulation should help you get rid of the colon.
You first need to format the value in "2011-10-06T12: 00: 00-08: 00".
Example: SimpleDateFormat dateParser = new SimpleDateFormat ("yyyy-MM-dd'T'HH: mm: ssZ");
After, create the formating for formataction desired.
Ex: SimpleDateFormat fmt = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss");
and after make parse for date.
Ex: Date date = dateParser.parse (dateFormat);
and print of date formated.
Below, one complete example.
String dataStr = "2011-10-06T12: 00: 00-08: 00";
SimpleDateFormat dataParser = new SimpleDateFormat ("dd / MM / yyyy HH: mm: ss", Locale.US);
Date date;
Try {
date = dataParser.parse (dataStr);
System.out.println (dateFormatter.format (date));
} cath (ParseException e) {
}
tl;dr
OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" )
.format(
DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US ) // Or Locale.CANADA_FRENCH and such.
)
Oct 6, 2011
java.time
The modern approach uses the java.time classes that supplant the troublesome old legacy date-time classes.
You input string is in a format that complies with the ISO 8106 standard. The java.time classes use these standard formats by default when parsing/generating strings. So no need to specify a formatting pattern.
Parse as an OffsetDateTime because your input strings includes an offset-from-UTC but not a time zone.
OffsetDateTime odt = OffsetDateTime.parse( "2011-10-06T12:00:00-08:00" ) ;
odt.toString(): 2011-10-06T12:00-08:00
Generate a string in your desired format. Let java.time automatically localize rather than hard-code formatting patterns.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.US ); // Or Locale.CANADA_FRENCH and such.
String output = odt.format( f );
output: Oct 6, 2011
When seralizing a date-time value as text, use the standard ISO 8601 formats rather than a localized format.
String output = odt.toLocalDate().toString() ;
2011-10-06
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.
Try with
SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
For a date format like 2013-06-28T00:00:00+00:00, this code should work:
SimpleDateFormat sdfSource = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
I am sure most of you got frustrated from the fact that SimpleDateFormat can not handle ISO8601 format. Here is my little trick to solve this nuisance.
Create a list of Know format you know that you will use for your application and apply SimpleDateFormat to the list. Now, in your formatDate() method, simple try all your known format and trap the Exception, then if still did not have a date, just use
Date d = javax.xml.bind.DatatypeConverter.parseDateTime("2013-06-28T00:00:00+00:00").getTime();
if (d == null)
try {
SimpleDateFormater ...
}
to try it and see if that work. For more info Simple trick to convert Date format with timezone in Java!
I'd strongly recommend using JodaTime for this sort of thing.
You're trying to parse an ISO Date format, and Joda does that 'out of the box', and will give you plenty of other benefits too.
I long ago gave up trying to get the standard JDK data classes to do helpful things.

Categories