Alexandr
Alexandr

Reputation: 726

Timestamp string to timestamp in java

I have the following string "2015-04-02 11:52:00+02" and I need to parse it in Java to a Timestamp. I tried all sorts of formats including

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z");

but nothing seems to work - I keep getting a ParseException

Can anyone help?

I need something like:

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss+Z");


Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00+02").getTime());

Upvotes: 0

Views: 734

Answers (4)

Basil Bourque
Basil Bourque

Reputation: 340200

ISO 8601

Replace that SPACE in the middle with a T and you have a valid standard (ISO 8601) string format that can be parsed directly by either the Joda-Time library or the new java.time package built into Java 8 (inspired by Joda-Time). Search StackOverflow for hundreds of examples.

If using java.time, read my comment on Question about a bug when parsing hours-only offset value.

Example in Joda-Time 2.7.

String inputRaw = "2015-04-02 11:52:00+02";
String input = inputRaw.replace( " ", "T" );
DateTimeZone zone = DateTimeZone.forID( "America/Montreal" );  // Specify desired time zone adjustment.
DateTime dateTime = new DateTime( input, zone );

Upvotes: 0

Neeraj Jain
Neeraj Jain

Reputation: 7720

Try This

String str="2009-12-31 23:59:59 +0100";
                               /\
                               ||
                      Provide Space while providing timeZone

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");
System.out.println(mdyFormat.parse(str));

Output

Fri Jan 01 04:29:59 IST 2010

Upvotes: 1

jhamon
jhamon

Reputation: 3691

try "yyyy-MM-dd HH:mm:ssX"

Z stand for timezone in the following format: +0800

X stand for timezone in the following format: +08

Examples here

Upvotes: 0

Felipe Sousa
Felipe Sousa

Reputation: 79

java.sql.Timestamp objects don't have time zones - they are instants in time, like java.util.Date

So try this:

SimpleDateFormat mdyFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Timestamp t = new Timestamp(mdyFormat.parse("2015-04-02 11:52:00").getTime());

Upvotes: 0

Related Questions