How to find the 24 hours difference based on Trip booked time - momentjs

From the API, I'm getting Trip booked Timezone(PST), Date-Time(2020-07-10 16:00:00). Now I want to check the 24 hours time difference with the user browser current time and display Cancel button otherwise, we need to hide the button. What I have done below is I'm passing trip booked time-2020-08-10 16:58:00 and booked timezone-PST which is getting from API then I'm finding the currentDate and taking the difference using the diff method. But I'm not getting current values. Any Help?
const departureDateWithTimeZone = moment.tz('2020-08-10 16:58:00', 'PST');
const currentDate = moment().format();
const diff = departureDateWithTimeZone.diff(currentDate, 'h');

Docs state that the last argument in moment.tz should be a time zone identifier.
Use America/Los_Angeles (or any other correct tz identifier) instead of PST:
const departureDateWithTimeZone = moment.tz('2020-08-10 16:58:00', 'America/Los_Angeles');
const currentDate = moment();
const diff = departureDateWithTimeZone.diff(currentDate, 'h');
console.log(`Current date: ${currentDate.format('YYYY-MM-DD HH:mm:ss Z')}`);
console.log(`Departure date: ${departureDateWithTimeZone.format('YYYY-MM-DD HH:mm:ss Z')}`);
console.log(`Diff in hours: ${diff}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.min.js"></script>

Related

How to fomat date UTC with moment.js?

I am struggling to understand how to work with moment.js (UTC):
without utc
const now = moment().format() // result: 2022-06-04T02:48:50+03:00 (that's correct, but i need a format like this: 2022-06-04T02:48:50 ).
with utc
const now = moment.utc().format() // result: 2022-06-03T23:50:54Z // the problem is that as you can see the result is behind 3 hours
How to handle this situation?

Moment.js, FullCalendar.js datetime comparisons with timezone offsets

I'm confused.
I have a textbox that is populated with a date and time (string) such as '09/07/2021 10:30'.
I convert this string to a moment like so:
var suggestedDateObj = moment(suggestedDate, 'DD/MM/YYYY HH:mm');
I then want to check if this date and time is in between time slots in a fullcalendar.js event object. I do this like so:
var startDateObj = moment(value.start);
var endDateObj = moment(value.end);
if (suggestedDateObj.isBetween(startDateObj, endDateObj)) {}
However...it isn't working. And it's due to timezone offset (i think).
suggestedDateObj returns a value with a UTC offset of +0100 (British Summer Time)
However my calendar event objects return a date with a UTC offset of +0000. So when i check if '09/07/2021 10:30 +0100' is in between '09/07/2021 10:30 +0000' and '09/07/2021 11:30 +0000' it doesn't work!
I guess my question is really either:
How can I create my suggestedDateObj moment with a timezone offset of zero? OR
How can i tell fullcallendar events that the time it is displaying is actually BST (+0100)? At the moment I don't specify the 'Timezone' parameter.
Thanks.
UPDATE
Hmm....this might work....although it feels a bit clunky:
var tmoment1 = moment(suggestedDate, 'DD/MM/YYYY HH:mm');
//create default date with specific timezone offset of zero
var suggestedDateObj = moment().utcOffset(0);
//set the date and time
suggestedDateObj.set({
day: tmoment1.day(),
month: tmoment1.month(),
year: tmoment1.year(),
hour: tmoment1.hour(),
minute: tmoment1.minute(),
second: 0
});
You can generate suggestedDateObj in utc like that:
var suggestedDateObj = moment.utc(suggestedDate, 'DD/MM/YYYY HH:mm');`
For the .isBetween() I suggest you to use the square bracket like forth parameter, like documentation says.
if (suggestedDateObj.isBetween(startDateObj, endDateObj, undefined, '[]'))
The square brackets indicate that the check must include the dates of the limiter

Why is moment.js date is 50 years ahead?

Using moment to format a date retrieved from a firestore timestamp. However the date is off by at least a day, and at most, a few months. and the year is off by 50 no matter what.
Here is the firestore timestamp
EDIT: Here is whats logged from lastMsg.seconds:
1581372232
I retrieve the time in seconds in a FlatList's renderItem:
renderItem={({ item, index }) => {
return (
<Components.InboxItem
title={item.withName}
subtitle={item.lastMsg.seconds}
img={item.withImg}
/>
);
And finally inside the component I use moment like so:
const date = moment()
.utc()
.startOf('year')
.seconds(props.subtitle)
.format('MMMM DD YYYY');
While ive tried multiple format configurations, the one that gets it closest to accurate is with .startOf("year"). Even then, date is being displayed as "February 09, 2070". If .startOf() is changed to "month", "day", or "hour", the date gets changed to sometime in march. How can this be fixed to display the date as in firestore?
Looking at the https://firebase.google.com/docs/reference/js/firebase.firestore.Timestamp we can either get JS Date object or use the toMillis method to get milliseconds.
Now the simple moment.js api for converting timestamp to moment object is given here https://momentjs.com/docs/#/parsing/unix-timestamp-milliseconds/
moment(Number);
Now you can apply format on the moment object like below:
moment(Number).format(String);
Your issue with wrong date is may be due to the use of utc and seconds together and not passing timestamp to moment()
Use moment.unix():
const props = {
subtitle: 1581372232
};
const date = moment
.unix(props.subtitle)
.format('MMMM DD YYYY');
console.log(date);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
because item.lastMsg.seconds is
The number of seconds of UTC time since Unix epoch 1970-01-01T00:00:00Z

moment toISOstring without modifying date

I have a date like "Thu Sep 01 2016 00:00:00 GMT+0530 (IST)" which I need to send to server as ISO-8601 utc time. I tried like :
moment(mydate).toISOString()
moment.utc(mydate).toISOString()
moment(mydate).utcOffset("+00:00").toISOString()
but I am getting the result like
2016-08-31T18:30:00.000Z
which is 1day behind my intended time. So what can I do to make moment ignore my local timezone and see it as UTC?
Edit:
The expected output is
2016-09-01T18:30:00.000Z
And no, the initial input isn't a string rather a javascript "new Date()" value.
Reason this happens:
This happens because .toISOString() returns a timestamp in UTC, even if the moment in question is in local mode. This is done to provide consistency with the specification for native JavaScript Date .toISOString()
Solution:
Use the same function and pass true value to it. This will prevent UTC Conversion.
moment(date).toISOString(true)
const date = new Date("2020-12-17T03:24:00");
const dateISOStringUTC = moment(date).toISOString();
const dateISOString = moment(date).toISOString(true);
console.log("Converted to UTC:" + dateISOStringUTC)
console.log("Actual Date value:" + dateISOString)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
I take the same problem today and find the solution.
Here is the solution: moment(date,moment.ISO_8601)
var date = new Date();
console.log("Original Date");
console.log(date);
console.log("After Moment Format");
console.log(moment(date,moment.ISO_8601));
Test Execution:
Moment Documentation: MomentJs

Why is my datetime-local input not being processed correctly by google apps script?

I'm trying to process a form with a datetime-local field to create a calendar event in a public google calendar. But when I run the program, all my dates default to December 31st 1969 at 4pm. Anyone have any ideas?
My script (which takes "form" as a parameter):
var event = cal.createEvent(form.myTitle, new Date(form.startTime+".000Z"), new Date(form.endTime+".000Z"));
Logger.log(form.startTime+" and "+form.endTime);
I added ".000Z" as per this solution, but I ran into the same problem even without adding it: Why does my Date object in Google Apps Script return NaN
What startTime and endTime are logged as:
2016-03-15T17:30 and 2016-03-15T19:30
But this is in the execution transcript:
Calendar.createEvent([NEW EVENT, Wed Dec 31 16:00:00 PST 1969, Wed Dec 31 16:00:00 PST 1969])
There are lots of ways to set a date object in JavaScript, but to set the correct date for a Google Calendar, you must do it in a very specific way. You must get the calendar time zone. For many people, if the users of their script are all in the same time zone, then the code will work. The problem comes when you have users across different time zones, or the time zone of the script is different than the time zone of the calendar. The code must construct a valid date string first, and then use the date string to create the date object. You can create a date object without a date string, and that would be preferable in most cases, because people can mess up the code to create the date string, but in this situation, you have no other choice (That I know of). Why? It's because of the time zone offset setting. The time zone offset setting is included in the date string. That is the key piece of information, that makes sure your dates will get set correctly, including for daylight savings.
function setCalendarEvent(){
var startTime = "2016-03-15T17:30";
var endTime = "2016-03-15T19:30";
//Always get the time zone of the calendar. If you don't do that, users accross different times zones will write bad dates
var calTimeZone = CalendarApp.getDefaultCalendar().getTimeZone();
//Construct a valid date string from the data
var startYr = startTime.slice(0,4);
var endYr = endTime.slice(0,4);
var startMonth = startTime.slice(5,7);
var endMonth = endTime.slice(5,7);
var startDay = startTime.slice(8,10);
var endDay = endTime.slice(8,10);
var startHrAndMin = startTime.slice(11,17);
var endHrAndMin = endTime.slice(11,17);
var startDateString = startMonth + "/" + startDay + "/" + startYr + " " + startHrAndMin + ":00 ";
var timeZoneOffset = Utilities.formatDate(new Date(startDateString),calTimeZone, "Z");
var startDateAsDate = new Date(startDateString + " " + timeZoneOffset);
Logger.log('startDateAsDate: ' + startDateAsDate)
};

Resources