Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat with TimeZone

Tags:

java

android

I'm trying to format date from java.util.Date. I need this format:

2016-06-10T13:38:13.687+02:00.

How correctly convert this from standard Date format

May 04 09:51:52 CDT 2009 ?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss z", Locale.getDefault());
sdf.format(new Date());

This code unfortunately return value without +02:00.

like image 930
Algeroth Avatar asked Jun 10 '16 11:06

Algeroth


People also ask

How do I add time zones to a date format?

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST. New!

What date is yyyy mm DDThh mm SSZ?

"YYYY-MM-DDThh:mm:ss-hh:mm" is ISO 8601 format.

Is SimpleDateFormat deprecated?

Class SimpleDateFormat. Deprecated. A class for parsing and formatting dates with a given pattern, compatible with the Java 6 API.

What can I use instead of SimpleDateFormat?

DateTimeFormatter is a replacement for the old SimpleDateFormat that is thread-safe and provides additional functionality.


2 Answers

Just turn your z to upperCase

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss Z", Locale.getDefault());
    sdf.format(new Date());

Result: 2016-06-10T13:53:22 +0200

like image 37
SCouto Avatar answered Sep 23 '22 06:09

SCouto


As per the standard Java docs: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

for getting date and time formatting of

2001-07-04T12:08:56.235-07:00


You Need to use below String pattern:

"yyyy-MM-dd'T'HH:mm:ss.SSSXXX"

So with below code, you can get what you want:

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.getDefault());
    simpleDateFormat .format(new Date());
like image 184
Shridutt Kothari Avatar answered Sep 22 '22 06:09

Shridutt Kothari