I am trying to convert a time&date string from the local time to UTC. Here is what I have :
I use fullcalendar, and when the user clicks a date it will trigger a modal and in the modal, there is a field for the user to pick a date example
For example, let's say that the user wants to use that date, now I need to convert it to UTC.
a =$('#Date').val();
console.log(a);
"December 20, 2021"
b = $('#Time').val();
console.log(b);
"12:30 AM"
c = a " " b;
console.log(c);
"12:30 AMDecember 20, 2021"
So I need the c variable converted to utc.
Now what I am having trouble with is the format,
y = selectedDate = moment(c, 'h:mm DD/MM/YYYY');
Is not working And I am not 100% sure how to do this correctly.
console.log(y.utc());
Object { _isAMomentObject: true, _i: "December 20, 2021 12:30 AM", _f: "h:mm DD/MM/YYYY", _isUTC: true, _pf: {…}, _locale: {…}, _d: Date Mon Dec 20 2021 20:30:00 (local time :D), _isValid: true, _ambigTime: false, _ambigZone: false, … }
Thank you!
CodePudding user response:
I really like Luxon (the successor to Moment).
You can use its methods DateTime.fromFormat
and DateTime.toUTC
to get the data you need:
<script type="module">
import {DateTime} from 'https://unpkg.com/[email protected]/build/es6/luxon.js';
const dateStr = 'December 20, 2021';
const timeStr = '12:30 AM';
const dtString = `${timeStr} ${dateStr}`;
const parseFormat = 'h:mm a MMMM d, y';
const locale = 'en-US';
const dt = DateTime.fromFormat(dtString, parseFormat, {locale});
const logInfo = (name, dt) => console.log(name, dt.toString(), dt.toObject());
logInfo('local', dt);
logInfo('utc', dt.toUTC());
</script>
CodePudding user response:
Seems like your parse string is wrong. You can use "MMMM DD, YYYY h:mm A"
as the parse string. Please check the below example.
const a= "December 20, 2021"
const b= "12:30 AM"
const c = `${a} ${b}`;
console.log(moment().format("MMMM DD, YYYY h:mm A"))
y = selectedDate = moment(c, "MMMM DD, YYYY h:mm A");
console.log(y.utc());
console.log(y.format("MMMM DD, YYYY h:mm A"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>