The issue is that, assume I’m selecting the following date and time
This is the code i have used to get this
<DateTimePicker
testID="datePicker"
value={date}
mode={'datetime'}
is24Hour={true}
// onChange={e => setDate(e.nativeEvent.timestamp)}
onChange={e => {
console.log('eee', e);
console.log(new Date(e.nativeEvent.timestamp));
setDate(new Date(e.nativeEvent.timestamp));
}}
/>
Now, my issue is that, it’s converting the selected time to UTC , all i want is to get the selected date and time irrelevant to the time zone user is in. I just want sept 5, 2023 8:49 AM
How do i get it ? I don’t want to do time zone conversions as that will mess up my use-case, Is there a way to get the selected date and time ? or is there any other react-native module that is easier to work with ?
2
Answers
You can try to use the function Date.UTC() instead of just
Date()
. This will treat all selected date-times relative to UTC-0, removing the need to handle the change. If converting it to string offsets the result to user’s local timezone, you can use getTimezoneOffset()All this can be handled inside your
onChange
functionThe component is already converting your datetime back to the user’s local timezone before displaying it. If you would like to use
date
elsewhere in your application, you must handle the timezone. Datetimes do not exist (and should not exist) without a timezone attached which allows you to localize it for a user.If you’d like to just display the datetime elsewhere in your app, try
to get something like
9/2/2023, 10:28:02 PM
. This will localize the datetime string from UTC to the user’s timezone for you.Also, you can directly access the date from the
onChange
function like this and avoid creating newDate
objects from timestamps: