How to use diff method in Luxon - javascript

I currently get a date from calendar control and using luxon I add days, minutes to it and change it to LongHours format like below:
newValue : is value i get from frontend(calendar control)
let formattedDate: any;
FormattedDate = DateTime.fromJSDate(new Date(newValue)).plus({ days: 1, hours: 3, minutes: 13, seconds: 10 }).toLocaleString(DateTime.DATETIME_HUGE_WITH_SECONDS)
console.log(formattedDate);
const formattedDateParsed = DateTime.fromJSDate(new Date(formattedDate));
const newValueParsed = DateTime.fromJSDate(new Date(newValue));
var diffInMonths = formattedDateParsed.diff(newValueParsed, ['months', 'days', 'hours', 'minutes', 'seconds']);
diffInMonths.toObject(); //=> { months: 1 }
console.log(diffInMonths.toObject());
Currently the formattedDateParsed is coming as 'Null'
Can I get some help as how to parse the date so that diff can be calculated

A few things going on here.
First, FormattedDate and formattedDate are different variables, so formattedDate isn't being set:
let formattedDate: any;
FormattedDate = DateTime.fromJSDate(new Date(newValue)).plus({ days: 1, hours: 3, minutes: 13, seconds: 10 }).toLocaleString(DateTime.DATETIME_HUGE_WITH_SECONDS)
console.log(formattedDate);
Second, you are converting to a string and then back into a DateTime, using the Date constructor as a parser, which isn't a great idea because a) it's unnecessary, and b) browsers aren't super consistent about which strings they can parse.
Instead, let's just convert once:
const newValueParsed = DateTime.fromJSDate(new Date(newValue));
const laterDate = newValueParsed.plus({ days: 1, hours: 3, minutes: 13, seconds: 10 });
const diffInMonths = laterDate.diff(newValueParsed, ['months', 'days', 'hours', 'minutes', 'seconds']);
diffInMonths.toObject(); // => {months: 0, days: 1, hours: 3, minutes: 13, seconds: 10}

Related

conversion of an object to UTC ISO time format

I have an object with time information.
const dateTime = {
day: 3,
hour: 18,
minute: 22,
month: 11,
second: 54,
timeZoneOffset: -60,
year: 2022
}
How do I convert this object to ISO UTC time format?
The Date API allows to build a date object with all your arguments.
You'd have to create a new Date object with your value, and then you can convert your object to the format you want (UTC ISO string...).
If the timezone is not the timezone of the locale machine, you'd have to workaround with the setTime method.
see
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Also see this answer for more info about setting time zone
const dateTime = {
day: 3,
hour: 18,
minute: 22,
month: 11,
second: 54,
timeZoneOffset: -60,
year: 2022
};
const {
day,
hour,
minute,
month,
second,
year,
timeZoneOffset
} = dateTime;
const d = new Date(Date.UTC(year, month, day, hour, minute, second));
d.setTime(d.getTime() + timeZoneOffset * 60000);
console.log(d.toISOString());
console.log(d.toUTCString());

How can I convert my date and time into an acceptable format for React Big Calendar

I am taking date, start time and end time of an event from the database, all of which are stored as strings in these format: eventDate: "2022-02-21", startTime: "20:30", endTime: "22:30" respectively. I need to pass 2022-02-21 8:30 PM as the start time and 2022-02-21 10:30 PM as the end time. From the docs that I read, I believe I have to have them in the array list of event objects as:
new Date(2022, 2, 21, 20, 30, 0) and new Date(2022, 2, 21, 22, 30, 0). These values are dynamic, so I won't manually be able to change them. What are some ways I can manipulate the values of date, startTime and endTime to be able to pass it to the calendar?
const s = new Date(2022, 2, 21, 20, 30, 0), e = new Date(2022, 2, 21, 22, 30, 0)
const eventDate = `${s.getFullYear()}-${s.getMonth().toString().padStart(2, `0`)}-${s.getDate().toString().padStart(2, `0`)}`
const startTime = `${s.getHours().toString().padStart(2, `0`)}:${s.getMinutes().toString().padStart(2, `0`)}`
const endTime = `${e.getHours().toString().padStart(2, `0`)}:${e.getMinutes().toString().padStart(2, `0`)}`
console.log(`eventDate:`, eventDate, `startTime:`, startTime, `endTime:`, endTime)

Getting exact format with momentjs and lodash

I have a list of times slots here eg:
const times = [
{ start: '2020-07-09T08:00:00.000+02:00', end: '2020-07-09T09:30:00.000+02:00' },
{ start: '2020-07-09T08:30:00.000+02:00', end: '2020-07-09T10:00:00.000+02:00' },
]
While I'm trying to sort them by day using momentjs and lodash to get something like:
{
{startTime: '08:00', endTime: '08:30'}
{startTime: '08:30', endTime: '09:00'}
{startTime: '08:00', endTime: '08:30'}
{startTime: '08:30', endTime: '09:00'}
}
and I ended up with this solution for now:
const groupedAndFormatted = groupBy(times, date => moment(date.start_time).startOf('day').format('MMM Do YY'))
But this one didn't really give me the correct solution, any ideas?
First you need to sort them into the correct order, we will do this with sort and unix time stamps.
Then group them with the dddd
const times = [
{ start_time: '2020-07-09T08:00:00.000+02:00', endTime: '2020-07-09T09:30:00.000+02:00' },
{ start_time: '2020-07-09T08:30:00.000+02:00', endTime: '2020-07-09T10:00:00.000+02:00' },
{ start_time: '2020-07-07T09:00:00.000+02:00', endTime: '2020-07-07T10:30:00.000+02:00' }
];
const sorted_times = times.sort((a,b) => moment(a.start_time).unix() - moment(b.start_time).unix())
const grouped = _.groupBy(sorted_times, date => moment(date.start_time).format("dddd"))
const formatted = _.mapValues(grouped, dates => {
return dates.map(times => {
return {
start_time: moment(times.start_time).format("hh:mma"),
endTime: moment(times.endTime).format("hh:mma"),
}
})
})
However this will not work if you end up having multiple tuesdays on different dates.

Parse Date from Array - JS

I have an array with a date. When I parse it, the month increases by 1. How can I fix it?
var data = [{
name: 'Arun',
date: [2019, 4, 9, 14, 55, 28, 897778]
}, {
name: 'Manohar',
date: [2019, 4, 3, 22, 43, 54, 894553]
}]
data.forEach((item) => {
item.date.pop()
item.date = new Date(...item.date).toLocaleString('en-US')
});
console.log(data)
I want the month as April and not May. Please advice.
As per the documentation suggests, the monthIndex would start at 0, rather than 1. So you need to manually subtract 1.
data.forEach((item) => {
item.date.pop()
item.date[1]--
item.date = new Date(...item.date).toLocaleString('en-US')
});
The month is represented by a value from 0 to 11, 4 is the fifth month, it corresponds to May, you just need to decrease it by 1.

How to use Moment.JS to check whether a timestamp is between 2 other timestamps

I have the following JSON array (note these are only the 5th and 6th elements of the array):
[
{
Day: 'Mon',
EndTime: '{ts \'1970-01-01 18:00:00\'}',
StartTime: '{ts \'1970-01-01 16:30:00\'}',
courseName: 'Computer Science 250: Introduction to Website Design',
Credits: '4'
},
{
Day: 'Mon',
EndTime: '{ts \'1970-01-01 18:30:00\'}',
StartTime: '{ts \'1970-01-01 17:30:00\'}',
courseName: 'Math 220: Differential Equations',
Credits: '3'
}
]
The data in the array is sorted by the values of the 'EndTime'. When I try to check whether the end time of the object at i - 1 (18:00:00) is between the start time and end time of the next object (at i which if 17:30:00 to 18:30:00) I should get true, but instead the isBetween method returns false.
How can I fix this, I know I am making some kind of simple mistake?
Here is my code:
for(let i = 1; i < monday.length-1; i++) {
const year = '1970-01-01';
const format = 'DD/MM/YYYY hh:mm:ss a';
var next_endtime = monday[i].EndTime.substr(16, 8);
var next_starttime = monday[i].StartTime.substr(16, 8);
var prev_endtime = monday[i-1].EndTime.substr(16, 8);
var plesson_e = moment(year + 'T' + prev_endtime, format),
nlesson_start = moment(year + 'T' + next_starttime, format),
nlesson_end = moment(year + 'T' + next_endtime, format);
var testbool = moment(plesson_e).isBetween(nlesson_start, nlesson_end, 'time');
console.log(testbool);
}
The string you pass to moment does not match your specified format :
const year = '1970-01-01'; // => see the '-', and the year is first
const format = 'DD/MM/YYYY hh:mm:ss a'; // => you put '/' and day first
Try changing the format value to:
const format = 'YYYY-MM-DD hh:mm:ss a';
See this fiddle
There is something wrong with the datetime or format, which you pass to moment JS, it works for me:
const monday = [{
Day: 'Mon',
EndTime: '{ts \'1970-01-01 18:00:00\'}',
StartTime: '{ts \'1970-01-01 16:30:00\'}',
courseName: 'Computer Science 250: Introduction to Website Design',
Credits: '4'
},
{
Day: 'Mon',
EndTime: '{ts \'1970-01-01 18:30:00\'}',
StartTime: '{ts \'1970-01-01 17:30:00\'}',
courseName: 'Math 220: Differential Equations',
Credits: '3'
}
]
const format = 'hh:mm:ss a';
var next_endtime = monday[1].EndTime.substr(16, 8);
var next_starttime = monday[1].StartTime.substr(16, 8);
var prev_endtime = monday[0].EndTime.substr(16, 8);
var plesson_e = moment(prev_endtime, format),
nlesson_start = moment(next_starttime, format),
nlesson_end = moment(next_endtime, format);
var testbool = moment(plesson_e).isBetween(nlesson_start, nlesson_end, 'time');
console.log(next_endtime, next_starttime, prev_endtime);
console.log(nlesson_end, nlesson_start, plesson_e);
console.log(testbool);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

Categories