I am new to React Native and I'm having the hardest time trying to do something I've done many times in PHP and other languages.
There are many ways to deal with time zone conversion and formatting of dates but, I'm just having no luck and I've spent WAY too much time on this.
Here is what I'm trying to do:
- Take the date which is coming from MariaDB/MySQL format like 2021-09-11 00:22:00 etc and is stored in UTC time. I have this in a variable and ready to go and convert in my React App.
- Convert MySql date as shown above to local time zone based on the user's device time zone OR a specified time zone which I can specify for this user (I store this in my DB already).
- Take the date in step 2 and format it in various ways like 12 hour format, 24 hour format, day of week version day number of the week and so on.
I'm able to do these things quite easily in PHP for example and I thought I had previously done similar in vanilla JS but can't remember. For the last two days I have been in this rabbit hole I fell down dealing with just dates.. Uggg help me get out.
I am currently using the code below and it does what I want on IOS and I thought I was done until I tested on Android and realized that it shows military time on Android. Uggg..
I have seen recommendations to use moment.js but when I looked over that it basically says that it's old school and it shouldn't be used for modern coding.
I am looking for something modern and not incredibly complicated, I don't think what I'm doing is incredibly complex Geesh.. Prefer not to use a library but will if I have to so I don't have to spend another 2 days screwing with a date conversion.
Here's what I have now in a component I made for my app. I'm sure it's horrible code wise but it works except on Android.
Thanks in advance for any help.
Here is what I have which outputs something like Fri 09/09/2021, 10:29 pm when I push a MySQL date into it. In Android is shows the same output but military (24 hour) time.
import React from 'react';
const DateConvert = (rawDate) => {
// Convert the date into local time based on handset
const msgDateLocal = new Date(rawDate);
let msgDateDay; // Convert the numeric weekday to something more readable ZERO based
switch (msgDateLocal.getDay()) {
case 0:
msgDateDay = "Sun";
break;
case 1:
msgDateDay = "Mon";
break;
case 2:
msgDateDay = "Tue";
break;
case 3:
msgDateDay = "Wed";
break;
case 4:
msgDateDay = "Thu";
break;
case 5:
msgDateDay = "Fri";
break;
case 6:
msgDateDay = "Sat";
break
default:
msgDateDay = "Invalid day of the week";
}
// Let's do a little formatting to make it all pretty
return `${msgDateDay} ${msgDateLocal.toLocaleDateString()} ${msgDateLocal.toLocaleTimeString()}`;
};
export default DateConvert;