Most of the time, while developing a React Native app, one has to deal with server-side data and time. Servers usually store the timestamp in UTC format. But on devices, we have to show in the user’s timezone. The following snippet converts the UTC time to the user’s time format
Getting the Current UTC time string
new Date().toISOString()Converting device local time to UTC time string
const convertLocalTimeToUTCTime = () => {
const dateString = '2025-03-27T00:00:00'
// Split Date and Time
const [fullDate, time] = dateString.split('T');
const [year, month, date] = fullDate.split('-');
const [hour, minute, second] = time.split(':');
const dateTime = new Date(year, month, date, hour, minute, second);
return dateTime.toISOString();
}
// Alternative Approach
const convertLocalTimeToUTCTime = (dateString) => {
const date = new Date(dateString)
if (Platform.OS === Platform.iOS) {
return date.toISOString()
}
return new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
).toISOString();
}Converting UTC date-time string to device’s local date-time
const convertUTCToLocalTime = (dateString) => {
const date = new Date(dateString)
const milliseconds = Date.UTC(
date.getFullYear(),
date.getMonth(),
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
);
const localTime = new Date(milliseconds)
return localTime
}