2

correct date format i am looking for:- "2017-07-06T18:03:39.195+0530"

how to get the +0530 for the current date in java ?

when i am using SimpleDateFormat it is giving +0000 , while it should give +0530 .

=================================================
i have tried using below :-

SimpleDateFormat format = new SimpleDateFormat("enter code hereyyy-MM-dd HH:mm:ss.SSS Z");
String dateString = format.format(new Date());
System.out.println("value of dateString is :"+dateString); 

the above code will output :- value of dateString is :2017-07-10 06:51:27.250 +0000

while it should output : +0530

can you please tell me how can i get the +0530 offset for the above date or current date ?

Ashish168
  • 162
  • 4
  • 14

4 Answers4

4

tl;dr

ZonedDateTime.now( ZoneId.of( "Asia/Kolkata" ) ).toOffsetDateTime().toString()

OffsetDateTime

To directly address the Question, use the modern OffsetDateTime class.

OffsetDateTime.now().toString()

See this code run live at IdeOne.com.

odt.toString(): 2019-08-22T17:44:00.219684Z

That will generate a string representing the current moment in the offset used by the JVM’s current default time zone using standard ISO 8601 format. One difference: This method will include the optional COLON : character between hours and minutes of the offset. I suggest never omitting that character as I have seen multiple libraries break on such input, expecting the COLON to be there.

When capturing the current moment, the result may resolve to microseconds. If you prefer milliseconds, truncate, lopping off the micros.

OffsetDateTime.now().truncatedTo( ChronoUnit.MILLIS ) 

odtTruncated.toString(): 2019-08-22T17:44:00.219Z

That code running at IdeOne.com is in a JVM where the offset is set to zero, for UTC itself. So we see a Z at the end, a common and standard alternative to +00:00, pronounced “Zulu”.

You may want to specify your offset explicitly.

Instant instant = Instant.now() ;  // Current moment in UTC.
ZoneOffset offset = ZoneId.of( "Asia/Kolkata" ).getRules().getOffset( instant ) ;  // We must pass a moment. India is currently at five and a half hours ahead of UTC. But it has not always been so in the past, and may not always be so in the future.
OffsetDateTime odt = instant.atOffset( offset ) ;

odt.toString(): 2019-08-22T23:00:06.925139+05:30

I think a cleaner syntax is to use ZonedDateTime.

String output = ZonedDateTime.now( ZoneId.of( "Asia/Kolkata" ) ).toOffsetDateTime().toString() ;

2019-08-22T23:03:19.072681+05:30

ZonedDateTime

More likely you should be getting the current moment in a time zone rather than a mere offset. If so, see the Answer by RaT.

Be clear on the difference between offset and zone:

  • An offset-from-UTC is merely a number of hours-minutes-seconds ahead of UTC or behind UTC.
  • A time zone is much more. A time zone is a history of past, present, and future changes to the offset used by the people of a particular region. A zone has a name in Continent/Region format, such as America/Montreal or Africa/Tunis.

Converting

Normally, you should avoid using the terrible date-time classes such as java.util.Date and SimpleDateFormat that are now legacy. Always use Instant, OffsetDateTime, and ZonedDateTime. Never use Date & Calendar.

But if you must you must use the legacy classes when interoperating with old code not yet updated for the java.time classes, you can convert back-and-forth. This is shown in the Answer by RaT.


Table of date-time types in Java (both modern and legacy) and in standard SQL

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
2

You can Use Java 8 DateTime API for another solution

ZoneId zone = ZoneId.systemDefault(); //It will give current System's timezone (IST for you)
Date date = new Date(); // Any date

DateTimeFormatter formatter= DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS Z", Locale.ENGLISH);

ZonedDateTime zonedTime = ZonedDateTime.ofInstant(date.toInstant(), zone);

System.out.println(zonedTime.format(formatter));

Above code will give you Date with correct Zone Offset

RaT
  • 1,134
  • 3
  • 12
  • 28
  • I just want to emphasize that normally you would never call `new Date()` as that legacy class is no longer used. The code on this Answer is appropriate only if you are interoperating with old code not yet updated to *java.time* and therefore need to convert between the legacy & modern classes via the new `to`/`from` methods added to the old classes. Otherwise, use only `Instant`, never `Date`. – Basil Bourque Aug 22 '19 at 17:28
1

After a lot of searching I found that the timezone problem can be solved with Joda time API. You can use below code to achieve what I want in my question:

DateTime dateTime = DateTime.now();
System.out.println(dateTime.toString("yyyy-MM-dd'T'HH:mm:ss.SSSZ"));

It outputs the current date with proper timezone:

2017-07-10T15:01:48.319+0530 
juzraai
  • 5,693
  • 8
  • 33
  • 47
Ashish168
  • 162
  • 4
  • 14
  • FYI, the [*Joda-Time*](http://www.joda.org/joda-time/) project is now in [maintenance mode](https://en.wikipedia.org/wiki/Maintenance_mode), advising migration to the [*java.time*](http://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes. See [Tutorial by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Aug 22 '19 at 17:29
0

Set the timezone you need. Your code would looke like:

SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS Z");
format.setTimeZone(TimeZone.getTimeZone("IST"));
String dateString = format.format(new Date());
System.out.println("value of dateString is :"+dateString);
krisp
  • 131
  • 5
  • as i cannot be sure if my code is being executed from india or us – Ashish168 Jul 10 '17 at 08:00
  • moreover there are different clients and different servers spread accross world , how will i be able to tell if it is IST or any other – Ashish168 Jul 10 '17 at 08:01
  • If you have different servers across the world, you should use UTC timezone in your machines. – Justinas Jakavonis Jul 10 '17 at 08:13
  • SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd HH:mm:ss.SSS Z"); format.setTimeZone(TimeZone.getTimeZone("UTC")); String dateString = format.format(new Date()); System.out.println("value of dateString is :"+dateString); – Ashish168 Jul 10 '17 at 08:19
  • value of dateString is :2017-07-10 16:13:43.646 +0000 , while timezone should be +0530 – Ashish168 Jul 10 '17 at 08:20
  • You have no timezone configured in your JVM. See https://stackoverflow.com/a/2493805/4326441 – krisp Jul 10 '17 at 08:49
  • Using ``TimeZone.getDefault()`` will give you current system's timezone – RaT Aug 22 '19 at 11:23
  • FYI, the terribly troublesome date-time classes such as [`java.util.Date`](https://docs.oracle.com/javase/10/docs/api/java/util/Date.html), [`java.util.Calendar`](https://docs.oracle.com/javase/10/docs/api/java/util/Calendar.html), and `java.text.SimpleDateFormat` are now [legacy](https://en.wikipedia.org/wiki/Legacy_system), supplanted by the [*java.time*](https://docs.oracle.com/javase/10/docs/api/java/time/package-summary.html) classes built into Java 8 and later. See [*Tutorial* by Oracle](https://docs.oracle.com/javase/tutorial/datetime/TOC.html). – Basil Bourque Aug 22 '19 at 17:29