I have the following code which gets current time in a certain format. This works perfectly fine locally when I test it out on my laptop.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS z");
ZonedDateTime date = ZonedDateTime.now();
String timeStamp = formatter.format(date);
This above works locally and the timestamp value is in following format:
2020-02-24 05:23:20.675 MST
But when I push it to production, the format changes to following:
2020-02-24 05:23:20.675 -07:00
I do not have access to the production settings and the team that handles it is in another timezone and will not be able to get them now. Believe it is some setting on their end but is there something I could do such that the format is always like: 2020-02-24 05:23:20.675 MST ?
Please advice, thanks.
You have to specify your time zone, it seems in production you are using a different time zone than the one in local. Beside in your code you don't specify any Zone, for that it took the default Zone.
To solve this, you have to specify the zone :
ZoneId zoneId = ZoneId.of("America/Dawson_Creek"); // specify the zone you want to use
ZonedDateTime date = ZonedDateTime.now(zoneId);
Related
I'am creating a date and store it into database, I want to get current time which is timezone = "Asia/Istanbul" not my local time.
I am creating the date in my local computer, my local timezone is also "Asia/Istanbul".
when i deploy it into my server, server timezone is utc, it is turning to utc everytime.
I have different 2 machine, 2 machines have different timezone so I need to set my data dates with the timezone.
here is what i have done. it is ok in my local computer, but fails on server which is UTC
LocalDateTime localDateTime = LocalDateTime.now();
// it gives my local date time, 2019-07-09T10:30:03.171
// local date is now 1:30 pm, UTC is 3 hours after, it looks ok.
ZonedDateTime zonedDateTime = ZonedDateTime.of(localDateTime, ZoneId.of("Asia/Istanbul"));
//2019-07-09T10:30:03.171+03:00[Asia/Istanbul]
// it looks +3. I dont want to see +3, I want the date like 01:30 which is shiefted
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
zonedDateTime.format(formatter);
//2019-07-09T07:30:03.171Z
// zone is disappeared, this is 3 hours before UTC
I expect the date like Asia/Istanbul when i created it.
I wouldn’t use LocalDateTime at all. Use ZonedDateTime throughout to eliminate any and all doubt about the time. Also always pass a ZoneId (if not a Clock) to the now method. This makes your code independent of the time zone settings of the computer and JVM.
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of("Asia/Istanbul"));
System.out.println(zonedDateTime);
2019-07-09T14:14:17.280852+03:00[Asia/Istanbul]
You might have misunderstood the +03:00 part, people sometimes do. It means that the time shown is already 3 hours ahead of UTC. So the point in time shown is equal to 11:14:17 UTC.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
System.out.println(zonedDateTime.format(formatter));
2019-07-09 14:14:17
Your formatter does not include time zone, therefore it’s not shown. But it’s the time in İstanbul.
What went wrong in your code?
I am assuming that the comments in your code are from running on your server in UTC (it’s not perfectly clear) and that you ran the code around 10:30 UTC, the same as 13:30 in İstanbul.
A LocalDateTime is a date and time without time zone and without UTC offset. Its no-arg now method uses the JVM’s time zone setting, in this case UTC, so gives you 10:30 on the day in question. I think that ZonedDateTime.of is wrong here: it takes the 10:30 from the LocalDateTime and İstanbul time zone from the ZoneId object and gives you 10:30 in İstanbul, which is not what you wanted. You had wanted 13:30, AKA 1:30 PM.
I have a time value stored in my database in HH:mm:ss format (using MySQL's time type). This time is to be considered as a value of IST timezone. The server on which my Java code runs follows the UTC timezone.
How can I get a formatted datetime in yyyy-MM-dd HH:mm:ss in IST (or in UTC millis)? Following is what I've tried till now:
// ... Code truncated for brevity
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalTime time = resultSet.getTime("send_time").toLocalTime();
LocalDateTime datetime = time.atDate(LocalDate.now());
System.out.println(datetime.format(formatter));
The above correctly prints the datetime on my local machine, which is on IST, but I'm concerned about how it will behave on the remote server.
Your approach is fine and should work regardless of your computer's time zone since there is no time zone information in either LocalTime or LocalDateTime. One possible issue is with LocalDate.now() which returns today's date in the computer's local time zone, not in IST. You may want to replace it with LocalDate.now(ZoneId.of("Asia/Calcutta")).
Or as commented by #OleV.V. you could use the new driver facilities to derive a LocalTime directly:
LocalTime time = resultSet.getObject("send_time", LocalTime.class);
Note possible caveats with your approach:
if the time zone you use introduces DST, you may end up with two identical times in your DB that were actually different instants - using UTC to store times is probably more robust
time in mysql can store values smaller than 00:00 and larger than 23:59:59.999999, in which case you may experience unexpected behaviours on the Java side.
I run the following code:
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
try{
Date date = sdf.parse("03-28-2003 01:00:00");
System.out.print(date.toString());
}
catch(Exception e){
//do something
}
The result of the parsing is this date: 2003-03-28T02:00:00.000+0300
One hour is added.
When I change the year/day/hour to any other valid number, I get the correct time, no extra hour is added. If I only change the minutes or the seconds I still get the added hour.
Can anyone tell me why this happens?
EDIT:
This is related to when daylight saving time is applied in the timezone my program runs on- UTC+02:00.
In this timezone the clock changed on 2003-03-28. that's why an hour was added, as it was suggested by the comments and answer below.
I used the code suggested in the answer to parse my date and the parsing worked! The date is parsed correctly, the extra hour isn't added.
Finding out exactly what your code does is complicated by the fact that not only SimpleDateFormat.parse() may depend on the default time zone of the computer (and does in this case where the pattern does not include time zone), also Date.toString() depends on the default time zone. However, I understand that you want to interpret the date string in UTC, so I will concentrate on getting the parsing right and not worry so much about what’s printed.
Feek is correct in the comment that setting the time zone of the SimpleDateFormat to UTC will get you what you want, for example:
sdf.setTimeZone(TimeZone.getTimeZone("Etc/UTC"));
With this line added before try I get this output on my computer:
Fri Mar 28 02:00:00 CET 2003
2 am. CET agrees with 1 UTC, so now the parsing is correct.
Allow me to add that if you can use the Java 8 date and time classes, I find the corresponding code somewhat clearer:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd-yyyy HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse("03-28-2003 01:00:00", formatter);
OffsetDateTime utcDateTime = dateTime.atOffset(ZoneOffset.UTC);
System.out.println(utcDateTime);
The point is not that it’s shorter, but that you don’t get easily in doubt about what it does and don’t easily get time zone or DST problems. An added benefit is that the output is also as expected:
2003-03-28T01:00Z
Now it’s evident that the time is correct (Z means Z or Zulu or UTC time zone, it’s got more than one name).
If for some reason you absolutely need an oldfashioned java.util.Date object, that is not difficult:
Date date = Date.from(utcDateTime.toInstant());
This gives the same date as we got from sdf.parse() with UTC time zone.
In a chat application, the server gave me this info regarding on the date that the message was created
2015-05-04 09:56:27
DateTime instance gives me this 2015-05-04T09:56:27.000+08:00
What I wanted to display on the chat bubble is this format
hh:mm a
My code doesn't seem to display the hours and minutes I wanted, instead it displays the hours and minutes in UTC
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime dt = formatter.parseDateTime(strDate);
String str = String.format("%s:%s %s",
dt.toString("hh"),
dt.toString("mm"),
dt.toString("a")
);
it displays like this 09:56 am instead of 5:56 pm. It seems like the +8 offset wasn't counted. I have tried the withOffsetParsed and it doesn't work too
DateTimeFormatter df = formatter.withOffsetParsed();
DateTime dt2 = df.parseDateTime(strDate);
Is there anything I missed?
If DateTime outputs 09:56:27.000+08:00, then that is your local time- and the UTC time is 1:56am.
However, if your expectation that this should output 5:56pm is correct, something else is wrong. The server is giving you a timestamp without a timezone specified, which is a bad API. Presumably this time should be interpreted as UTC?
Try adding .withZoneUTC() to the creation of the DateTimeFormatter. This will make it interpret the time fields of the string as UTC and should produce a DateTime of 09:56:27.000Z. You'll then need to convert this is a DateTime in your local timezone to display it, by calling .withZone(DateTimeZone.getDefault()) (or whatever means you have to get the appropriate timezone for the user, for example)
(You could be pedantic and call parseLocalDateTime to get a LocalDateTime since that is what the server is sending, but personally I'd just encapsulate the UTC rule into the formatter and pull a full DateTime straight out)
For our Russia tenant we are using "Europe/Moscow" timezone. But we are getting time with 1 hour ahead of the correct time.
Europe/Moscow is UTC+3 hours. But when I am print date formated with Europe/Moscow timezone getting 1 hour ahead of the correct time.
Thanks,
Syamala.
Java 8:
System.out.println(LocalDateTime.now(ZoneId.of("Europe/Moscow"))
.format(DateTimeFormatter.ofPattern("d.MM.yyyy 'um' HH:mm 'Uhr'")));
I notice that there was a legislative change to Russian time zone definitions in October 2014; chances are that your JRE simply doesn't know about it yet.
The Java Timezone Updater Utility should be able to fix this for you. As time passes, the updated time zone definitions should also eventually get included by default in newer JREs (although that admittedly doesn't help you right now).
you can use the joda-time api, version need greater than 2.5.because joda-time api update the timezone db after Russian time zone change from version 2.5.
Date timestamp = sdf.parse("11/17/2014 06:13:19");
TimeZone timezone = TimeZone.getTimeZone("Europe/Moscow");
DateTimeZone tz = DateTimeZone.forTimeZone(timezone);
DateTime jodaDateTime = new DateTime(timestamp, tz);
System.out.println(jodaDateTime.hourOfDay().get());
try threeteen
import org.threeten.bp.format.*
import org.threeten.bp.*
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String timestamp = dtf.format(ZonedDateTime.ofInstant(Instant.ofEpochMilli(MILLISECONDS_VALUE_HERE), ZoneId.of("Europe/Moscow"));