Joda DateTimeFormat list of timezones - calendar

I just discover CET is not a valid timezone for Joda time:
DateTimeFormatter DATE_TIME_FORMATTER =
DateTimeFormat.forPattern("dd/MM/yyyy HH:mm:ss.SSS z");
DateTime.parse("25/11/2016 11:50:00.000 CET", DATE_TIME_FORMATTER)`
-> java.lang.IllegalArgumentException: Invalid format: "25/11/2016 11:50:00.000 CET" is malformed at "CET"`
DateTime.parse("25/11/2016 11:50:00.000 PST", DATE_TIME_FORMATTER)`
-> OK
What is the official list of timezones? CET is a valid value for java.util.Calendar, but apparently not in Joda. The documentation doesn't say a lot.

The documentation you cited also says:
Zone names: Time zone names ('z') cannot be parsed.
Otherwise, if you use the DateTimeFormatterBuilder then you could use its method appendTimeZoneName(Map<String,DateTimeZone>) with specifying a lookup-map. By default, this lookup-map is given by the helper method DateTimeUtils.getDefaultTimeZoneNames() which only yields the English names of some US-located timezones:
•UT - UTC
•UTC - UTC
•GMT - UTC
•EST - America/New_York
•EDT - America/New_York
•CST - America/Chicago
•CDT - America/Chicago
•MST - America/Denver
•MDT - America/Denver
•PST - America/Los_Angeles
•PDT - America/Los_Angeles
Solution: Define your own lookup-map containing the string "CET", or use a better library for timezone-name-parsing (for example: Java-8 aka java.time-package does it better).

Related

timezone conversion using date-fns

I’m trying to work with date-fns-tz in my react-based webpage and couldn’t make the following use-case to work.
I have a date input in a form that should be submitted to the backend that stores the data in local timezone.
A user in GMT+2 timezone selects 14:00 on 1/Feb/2021 in the UI, which correlates to 1612180800 timestamp (as the UI was opened in GMT+2), but it should eventually get sent to the backend as 14:00 in GMT-8, which is actually 1612216800 timestamp.
What’s the right way to get this conversion (from 1612180800 --> 1612216800 ) to work?
I tried to work with various date-fns functions, but hadn’t found the right one.
You'll need two things to make this work correctly:
An IANA time zone identifier for the intended target time zone, such as 'America/Los_Angeles', rather than just an offset from UTC.
See "Time Zone != Offset" in the timezone tag wiki.
A library that supports providing input in a specific time zone.
Since you asked about date-fns, you should consider using the date-fns-tz add-on library.
Alternatively you could use Luxon for this.
In the past I might have recommended Moment with Moment-TimeZone, but you should review Moment's project status page before choosing this option.
Sticking with date-fns and date-fns-tz, the use case you gave is the very one described in the docs for the zonedTimeToUtc function, which I'll copy here:
Say a user is asked to input the date/time and time zone of an event. A date/time picker will typically return a Date instance with the chosen date, in the user's local time zone, and a select input might provide the actual IANA time zone name.
In order to work with this info effectively it is necessary to find the equivalent UTC time:
import { zonedTimeToUtc } from 'date-fns-tz'
const date = getDatePickerValue() // e.g. 2014-06-25 10:00:00 (picked in any time zone)
const timeZone = getTimeZoneValue() // e.g. America/Los_Angeles
const utcDate = zonedTimeToUtc(date, timeZone) // In June 10am in Los Angeles is 5pm UTC
postToServer(utcDate.toISOString(), timeZone) // post 2014-06-25T17:00:00.000Z, America/Los_Angeles
In your case, the only change is that at the very end instead of calling utcDate.toISOString() you'll call utcDate.getTime().
Note that you'll still want to divide by 1000 if you intend to pass timestamps in seconds rather than the milliseconds precision offered by the Date object.
You can use 'moment' to convert timezone.
1.Create a moment with your date time, specifying that this is expressed as utc, with moment.utc()
2.convert it to your timezone with moment.tz()
For example
moment.utc(t, 'YYYY-MM-DD HH:mm:ss')
.tz("America/Chicago")
.format('l');

angularjs Date Daylightsaving issue

I am using date to display my date on html like:
{{updateDate| date: 'dd/MM/yyyy HH:mm:ss'}}
Dates are all saved in UTC. The problem is it displays the date in locale timezone but not considering Daylight saving on/off. As in for BST it always shows +1 hr from UTC.
I want it to also consider DST(daylight saving time).
Any help, please.
{{ date_expression | date : format : timezone}}
As per angular date filter documentation:
date: Here date can be Date Object, milliseconds or ISO 8601 datetime string formats (like: e.g. yyyy-MM-ddTHH:mm:ss.sssZ). Here Z is 4 digit (+sign) representation of the timezone offset (-1200-+1200). If no timezone is specified in the string input, the time is considered to be in the local timezone.
format: this is optional, If not specified, mediumDate(equivalent to 'MMM d, y' for en_US locale (e.g. Sep 3, 2010)) is used.
timezone: Timezone to be used for formatting. It understands UTC/GMT and the continental US time zone abbreviations, but for general use, use a time zone offset, for example, '+0430' (4 hours, 30 minutes east of the Greenwich meridian) If not specified, the timezone of the browser will be used.
This may help you.

Timezone offset not working in angular js date expression

I have 2016-10-21T13:47:02.922452 as ISO string from backend server.
My timezone is +0530 GMT i.e Offset is +530 (ahead of GMT).
When i use angular date expression like this
{{'2016-10-21T13:47:02.922452'| date:'medium':'+530'}}
I expected output to be = Oct 21, 2016 7:17:02 PM
but it prints
Oct 21, 2016 1:47:02 PM instead.
I am confused for what am i doing wrong here.
Do something like this
var d = new Date('2016-10-21T13:47:02.922452');
console.log(d)
Answering myself !
The easiest way that i figured out ! Make a custom filter
app.filter('IST', function($filter){
return function(val){
var date = new Date(val);
return $filter(date, 'medium');
}
})
Then use filter in expression like this -
{{'2016-10-21T13:47:02.922452'| IST}}
Custom filter will automatically convert ISO format string to Date object (browser timezone will automatically take care of timezone conversion.)
Date pipe transforms the date string you are passing ('2016-10-21T13:47:02.922452') to a Date object and then applies the time zone offset.
¿Whats the problem? When transforming '2016-10-21T13:47:02.922452' to a Date, it supposes that the date is in your local time, so the final calculation is wrong. For example, I am in +0200 so the transformation will be:
2016-10-21T13:47:02.922452 -> 2016-10-21T13:47:02.922452+0200 (Date object)
2016-10-21T13:47:02.922452+0200 -> 2016-10-21T18:17:02.922452+0530 (date changes with offset difference 0530-0200)
If your backend date is always in GMT timezone, just add Z to your date string: 2016-10-21T13:47:02.922452Z. This way, when creating the Date it will understand that the initial timezone is +0000
Solution:
{{'2016-10-21T13:47:02.922452Z' | date:'medium':'+0530'}}

Why timezone in angular doesn't work as expected in the following case

I'm using legacy AngularJS 1.3
I have the following code
{{ (1475586000*1000) | date:'yyyy-MM-dd' : 'Australia/Lord_Howe'}}
In UTC, 1475586000 is 04 Oct 2016 13:00:00 GMT
Since Australia/Lord_Howe is +11, I expect 2016-10-05 should be printed.
However, 2016-10-04 is printed. May I know why?
From the docs for AngularJS v1.3.19 ...
Timezone to be used for formatting. Right now, only 'UTC' is
supported. If not specified, the timezone of the browser will be used.
Looking at the documentation for the latest 1.5 release ...
Timezone to be used for formatting. It understands UTC/GMT and the
continental US time zone abbreviations, but for general use, use a
time zone offset, for example, '+0430' (4 hours, 30 minutes east of
the Greenwich meridian) If not specified, the timezone of the browser
will be used.
... which gives the clue that you can get closer to what you want by using an offset, although that presumably gives daylight savings issues so it is not the same thing:
{{ (1475586000*1000) | date:'yyyy-MM-dd' : '+11:00'}}

Timezone issues when sending Calender entries using Java mail API

We are using JavaMail API to send calendar entries. But the recipients of Outlook have time zone issues, as meetings show wrong timings. In general our approach is as follows:
First of all we have,
SimpleDateFormat iCalendarDateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss");
we then use iCalendarDateFormat.setTimeZone(TimeZone.getTimeZone(receiverTimeZone));
Finally, we use Calendar.getInstance() for start and end to manipulate Calendar fields,
and hence we have Date startDate = startTime.getTime();
Date endDate = endTime.getTime();
When we are about to send request as per icalendar specification we have ,
"DTSTAMP:" + iCalendarDateFormat.format(startDate) + "\n" +
"DTSTART:" + iCalendarDateFormat.format(startDate)+ "\n" "DTEND:" + iCalendarDateFormat.format(endDate)+ "\n"
Is this the correct approach?. Please comment.
Thanks
tl;dr
iCalendar format tracks the date-time separately from its intended time zone. You must juggle both parts appropriately.
Always use java.time classes. Never use legacy classes like Calendar & SimpleDateFormat.
Details
Caveat: I have not used iCalendar data before. So I may be incorrect in my understanding.
Looking at pages 31-33 of the RFC 5545 spec, it seems the authors of that spec assume you always want the date-time to be recorded separately from the time zone.
A moment, a point on the timeline, needs the context of a time zone or offset-from-UTC. For example, "noon on the 23rd of January next year, 2021" is not a moment. We do not know if you mean noon in Tokyo Japan, noon in Toulouse France, or noon in Toledo Ohio US — all very different moments, several hours apart.
To provide the context of an offset, a date and time must be accompanied by a number of hours-minutes-seconds such as 08:00. For an offset of zero hours-minutes-seconds, use +00:00.
2021-01-23T12:00:00+00:00
As an abbreviation of an offset of zero, +00:00, the letter Z can be used, pronounced “Zulu”. For example:
2021-01-23T12:00:00Z
But, strangely, the iCalendar spec wants to track the date and the time-of-day separate from the time zone. So this:
2021-01-23T12:00:00
…and a time zone field elsewhere:
America/New_York
And the iCalendar spec opts for the harder-to-read “basic” variation allowed by ISO 8601, which minimizes the use of delimiters. So this:
20210123T120000
For such a string, we must parse as a LocalDateTime. This class represents a date with a time-of-day but lacking any time zone or offset-from-UTC.
DateTimeFormatter f = dateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" ) ;
String input = "20210123T120000" ; // “Basic” variation of ISO 8601 format.
LocalDateTime ldt = LocalDateTime.parse( input , f ) ;
To determine a moment, we must apply a time zone. I assume iCalendar uses proper time zone names (Continent/Region format) and not the 2-4 letter pseudo-zones such as PST, CST, IST, and so on.
String zoneName = receiverTimeZone ; // Variable name taken from your code example, though you neglected to show its origins.
ZoneId z = ZoneId.of( zoneName ) ;
Apply the zone to get a ZonedDateTime, a moment, a point on the timeline.
ZonedDateTime zdt = ldt.atZone( z ) ;
Going the other direction, let's start with the current moment.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime now = ZonedDateTime.now( z ) ;
And generate string values for iCalendar.
DateTimeFormatter f = dateTimeFormatter.ofPattern( "uuuuMMdd'T'HHmmss" ) ;
String iCal_DateTime = now.format( f ) ;
String iCal_ZoneName = now.getZone().toString() ;
Never use the terrible legacy date-time classes bundled with the earliest versions of Java: Calendar, GregorianCalendar, java.util.Date, SimpleDateFormat, and so on. These were supplanted years ago by the modern java.time classes defined in JSR 310.
Hard to tell without seeing the actual content of your iCalendar file, along with the expected start and end datetime with timezone information but you seem to be generating the DTSTART in floating time (datetime with local time). Although your code sample seems to imply that you have access to the recipient's timezone (receiverTimezone), this is a very fragile approach.
Instead, you should use either the datetime with UTC time or the datetime with local time and timezone (where the timezone does not have to be the receiver timezone).
If the event is not recurring, the most simple approach is to use datetime with UTC time.
See https://www.rfc-editor.org/rfc/rfc5545#section-3.3.5 for the definition of each format.
I had same problem, for which I struggle lot. So below are my findings:
Outlook works smoothly with UTC Timezone. If we set date & time with UTC Timezone then outlook automatically converts this UTC Time into user corresponding Timezone. We will have to use 'Instant' object for DTSTART:, DTEND: and for DTSTAMP(Optional but recommended) also.
Quick Test just use "DTSTART:"+Instant.now() in ical String.
And in Java 8 for getting UTC Time java time API provides Instant.now() through which you can get your system time in UTC format. Java 8 also provides method like
a. Instant.ofEpochMilli() - This returns Instant which can directly use in ical Sting.
b. new Date().toInstant() Which returns UTC Instant object.
There are few scenarios where input date and time sources are different:
If you are fetching Date and Time from database then in this case database is not storing Timezone its only saving Date & Time. So first convert the Date & Time in that Timezone in which it was saved in database, in my case I was storing Date & Time after converting in 'EST' Timezone and Date value was of EST but time zone was not there in DB. So while fetching Date & Time value from DB I have appended Timezone in the Date value and then further converted to EPOC time using below method
public static long getEpocTimeWithTimezone(Date date) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateTimeFormatter dateTimePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime dateTime = LocalDateTime.parse(simpleDateFormat.format(date), dateTimePattern);
long epochInMilliSeconds = dateTime.atZone(ZoneId.of("America/New_York")).toEpochSecond() * 1000;
return epochInMilliSeconds;
}
Then Just Use as below code for ical String:
Instant startDt = Instant.ofEpochMilli(getEpocTimeWithTimezone(//pass your date here
)).truncatedTo(ChronoUnit.MINUTES);
Now set this Instant object(startDt) directly to "DTSTART:":
"DTSTART:"+startDt+"....then in same fashion "DTEND:" also.
In second scenario you have Date with Timezone (make sure after conversion you did not loses your actual Timezone, Like in 1st scenario after saving Date in DB we actually lost Timezone but it was showing Timezone IST that was dummy so be careful about this)
So in this case just assume myDateObject is Date object. So just get the Instant (which
will be in UTC) object from myDateObject by using toInstant() of Date class.
Instant startDt = myDateObject.toInstant().truncatedTo(ChronoUnit.MINUTES);
I am using .truncatedTo(ChronoUnit.MINUTES); because if we will not use this then
we might get some extra min or second in Meeting invite Time section.
So the final String for outlook mail should be some like:
.
.
.
"BEGIN:VEVENT\n"+
"DTSTART:"+startDt+"\n"+
"DTEND:"+endDt+"\n"+
.
.
.
VVI Note: Since Z is representation of UTC time zone, So just adding Z in the last of Time will not be UTC zoned Time, You will have to convert the Date & Time then only accurate time will come on Outlook. For verifying your Time is in UTC format or not just save the .ics attached file (which you got in Email) in local and check Date & Time are coming as DTSTART:2020-05-15T13:57:00Z or not If not then you are not converting the Date correctly in UTC.

Resources