We need to take a datetime string (which we’ve already received and validated from user form inputs), treat it as being specific to the America/New_York
timezone, and convert it to UTC
.
We’re currently running ColdFusion 2018, which is limited in its native datetime functionality. So I wanted to tap into the underlying Java. Most CF-related solutions are pre-java.time
, so I attempted my own based on other Stack Overflow answers. Hoping someone with more Java knowledge can review this solution. (This is in CF Script, but it should be pretty self-documenting.) Is this correct and is there a better/more efficient solution?
var validatedDateTime = '2022-06-29T14:30:00'; LocalDateTime = createObject('java', 'java.time.LocalDateTime'); ZoneID = createObject('java', 'java.time.ZoneId'); ZoneOffset = createObject('java', 'java.time.ZoneOffset'); ldt = LocalDateTime.parse(validatedDateTime); nyZone = ZoneID.of('America/New_York'); odt = ldt.atOffset(nyZone.getRules().getOffset(ldt)); utcDateTime = odt.withOffsetSameInstant(ZoneOffset.UTC).toLocalDateTime();```
Advertisement
Answer
tl;dr
You said:
The question is more about taking a datetime string (e.g. ‘2022-06-29T14:30:00’), adding the America/New_York timezone to it, and converting it to UTC.
LocalDateTime .parse( "2022-06-29T14:30:00" ) // “taking a datetime string (e.g. '2022-06-29T14:30:00')” .atZone( ZoneId.of( "America/New_York" ) // “adding the America/New_York timezone to it” ) // Returns a `ZonedDateTime` object. .toInstant() // “converting it to UTC”
See this code run live at Ideone.com.
2022-06-29T18:30:00Z
Details
You neglected to mention your database engine and the precise type of your column. So we cannot give a full answer. I can address part of it.
So the goal is to take the user’s date & time, treat it like America/New_York, and convert it to UTC.
DateTimeFormatter fDate = DateTimeFormatter. … ; // Define a formatter to match the format used by your user. LocalDate ld = LocalDate.parse( inputDate , fDate ) ;
Trap for DateTimeParseException
to detect faulty inputs.
Do similarly for LocalTime
.
DateTimeFormatter fTime = DateTimeFormatter. … ; // Define a formatter to match the format used by your user. LocalTime lt = LocalDate.parse( inputTime , fTime ) ;
Combine with time zone to determine a moment.
ZoneId z = ZoneId.of( "America/New_York" ) ; ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;
Adjust to UTC.
Instant instant = zdt.toInstant() ;
All of this has been covered many many times on Stack Overflow. Search to learn more.