cancel
Showing results forย 
Search instead forย 
Did you mean:ย 

Converting Datetime with AM/PM to 24Hr date format

anubhav_nautiya
Contributor

Hi, I have a requirement where from the source file. I am getting date as string value โ€˜10/21/2019 6:16:54 PMโ€™, I want the date to be converted into yyyy-mm-dd hh:mm:ss format.
In the example given above the output should be โ€˜2019-10-21 18:16:54โ€™.
8/3/2019 4:24:00 AM for this input output should be 2019-08-03 04:24:00
for 7/3/2019 12:09:45 PM output should be 2019-07-03 12:09:45

I was able to achieve this using a complex regex but if anyone has a better way to do this please reply to this thread.

Regards
Anubhav

1 ACCEPTED SOLUTION

Hi Chris,
Thanks for your inputs, I was able to achieve this by using the expression below,
Date.parse($dt,โ€˜MM/dd/yyyy h:m:s aโ€™).toLocaleDateTimeString({โ€œformatโ€:โ€œyyyy-MM-dd HH:mm:ssโ€})

Regards
Anubhav

View solution in original post

5 REPLIES 5

dmiller
Admin Admin
Admin

It looks like using uppercase Hโ€™s works:

yyyy-mm-dd HH:mm:ss

Date.now().toLocaleDateString({"format":"yyy-mm-dd HH:mm:ss"}) = 2020-16-10 16:16:57


Diane Miller
Community Manager

Thanks Diane for taking time and responding, my problem however is when I do Date.parse($date) where $date = 10/21/2019 6:16:54 PM the result is NaN, since this string is not being parsed as date I am not able to use the toLocaleDateString function. I am using the below regex to achieve this

$Date.split(โ€™ โ€˜)[1].split(โ€™:โ€˜)[0]==โ€˜12โ€™? Date.parse($Date.replace(โ€™ PMโ€™,โ€˜โ€™)).toLocaleDateTimeString({โ€œformatโ€:โ€œyyyy-MM-dd HH:mm:ssโ€}):($Date.contains(โ€˜PMโ€™)? Date.parse($Date.replace(โ€™ PMโ€™,โ€˜โ€™)).plusHours(12).toLocaleDateTimeString({โ€œformatโ€:โ€œyyyy-MM-dd HH:mm:ssโ€}): Date.parse($Date.replace(โ€™ AMโ€™,โ€˜โ€™)).toLocaleDateTimeString({โ€œformatโ€:โ€œyyyy-MM-dd HH:mm:ssโ€}))

Thanks
Anubhav

When using the Date.Parse() function to parse a string, you must also pass a โ€œformatโ€ parameter, which specifies how your string is formatted.

parse(dateString, format) - Parse a date string using a custom format. The second argument is a format string using the same syntax as the Java SimpleDateFormat class.

Hi Chris
I tried what you mentioned in your comment, however I dont get the expected result, its not able to distinguish between AM and PM and gives same result for both

$dt = 11/12/2019 11:15:00 PM
expected output is 2019-11-12 23:15:00

image