I have a web application that deals with different time zones. This app stores all the dates in UTC + 00:00
and converts the time to local time right before displaying it using a set of functions I wrote.
It all works well from converting the date string
to a datetime object
, converting the datetime object
from UTC +00:00
to local time, but after I obtain the local datetime string
using date.toLocaleString()
, I cannot format it as I want because it returns the following format: 3/23/2021, 9:19:00 PM
, and literally all apple devices I tried cannot parse this string and convert it to a valid date.
I simply want to get the local time and format it from 3/23/2021, 9:19:00 PM
to 23 Mar 2021 21:19
. I have written a function that does this formatting for me but the browser cannot parse 3/23/2021, 9:19:00 PM
from a string and convert it to a date object
.
I am developing the application in React JS (JavaScript).
Here is the function that does the string parsing and date formatting:
const formatDateString = date => {
const parsed = new Date(Date.parse(date.replace(",", "")))
const months_string = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
const months_array = months_string.split(" ")
let output = ""
output = output + parsed.getDate() < 10 ? "0" + parsed.getDate() : parsed.getDate()
output = output + " " + months_array[parsed.getMonth()]
output = output + " " + parsed.getFullYear()
let hours = parsed.getHours() < 10 ? "0" + parsed.getHours() : parsed.getHours()
output = output + " " + hours
let minutes = parsed.getMinutes() < 10 ? "0" + parsed.getMinutes() : parsed.getMinutes()
output = output + ":" + minutes
return output
}
I ended up avoiding the parsing problem altogether and creating my own parser that will work for MY scenario. This solution only applies if your input format is same as mine, although it can be modified to work with virtually any date format. Here is the code:
export const formatDateStringApple = date_string => {
const months_string = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
const months_array = months_string.split(" ")
const split_datetime = date_string.split(" ")
const date = split_datetime[0].replace(",", "")
const _split_time = split_datetime[1].split(" ")
const time = _split_time[0]
const isPm = _split_time[1] == "PM" ? true : false
const split_date = date.split("/")
const split_time = time.split(":")
return `${split_date[1]} ${months_array[split_date[0] - 1]} ${split_date[2]} ${isPm ? split_time[0] + 12 : split_time[0] < 10 ? "0" + split_time[0] : split_time[0]}:${split_time[1]}`
}
Maybe (probably) there is a better way of doing this, but this is the quickest one I could come up with.