Invalid Date with datejs - javascript

I need to convert string to date.
But I don't understand why the end date is not converted from a string. Then I decided to use the daysJs library, but it gave the same thing
let date={
end:"15-10-2022",
start:"05-10-2022",
}
let range = {
start:new Date(date.start),
end: new Date(date.end),
};
console.log(range)

Running the code snippet embedded in Stack, I can see that your end property is null, presumably because the formattign for the dates is MM-DD-YYYY and you're formatting them as DD-MM-YYYY. The simplest solution is to Swap your month and day in the date. Otherwise, just use MomentJS for its simplification of working with dates.
Formatting DD-MM-YYYY without moment:
let date = {
end: '15-10-2022',
start: '05-10-2022'
};
let range = {
start: new Date(date.start.split('-').reverse().join('-')),
end: new Date(date.end.split('-').reverse().join('-'))
};
console.log(range);
Formatting DD-MM-YYYY with moment:
let date = {
end: '15-10-2022',
start: '05-10-2022'
};
let range = {
start: moment(date.start, 'DD-MM-YYYY'),
end: moment(date.end, 'DD-MM-YYYY')
};
console.log(range);

first number is month so 15 is undefined
let date={
end:"10-10-2022",
start:"05-10-2022",
}
let range = {
start:new Date(date.start),
end: new Date(date.end),
};
console.log(range)

The date format is wrong. Use YYYY-MM-DD

Related

Check if given date is in last 3 weeks

I have a sample date:
const date = '10-03-2022';
I need to check if this date is longer than 3 weeks or not. Or speaking differently - I need to check if this date is in the last 3 weeks or older.
I was trying with date-fns but its not the result I expect.
import { formatDistance, subWeeks } from 'date-fns'
formatDistance(subWeeks(new Date(), 3), date)
I dont have to be honest any idea how to deal with such problem. Thats why I wanted to ask you here for help. Thanks!
You can use isAfter to compare against subWeeks. This will return true even if the date is in the future from now.
Alternatively you can use isWithinInterval to test if the date is within the period between now and three weeks before now. (not included in the cdn version available).
const dateIsWithinInterval = isWithinInterval(testDate,
{ start: subWeeks(new Date(), 3), end: new Date() })
You'll still need to parse your string into a valid Date object.
//import { isAfter, subWeeks } from 'date-fns';
const { isAfter, subWeeks } = dateFns; // cdn assignment
const dateString = '10-06-2022';
const [d, m, y] = dateString.split('-').map(n => parseInt(n, 10));
// months are 0 indexed so you need to subrtract 1.
const testDate = new Date(y, m - 1, d);
const dateIsAfter = isAfter(testDate, subWeeks(new Date(), 3));
console.log('isAfter:', dateIsAfter);
<script src="https://cdnjs.cloudflare.com/ajax/libs/date-fns/2.0.0-alpha0/date_fns.min.js" integrity="sha512-0kon+2zxkK5yhflwFqaTaIhLVDKGVH0YH/jm8P8Bab/4EOgC/n7gWyy7WE4EXrfPOVDeNdaebiAng0nsfeFd9A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Convert moment.js to date-fns

I need to convert this from moment.js moment(date, 'DD MM YYYY').isBefore(moment()) to date-fns.
I tried isBefore(format(value, 'dd-MM-yyyy'), sub(new Date(), { days: 1 })). I mention that now I have to substract 1 day.
So the functionality will be to compare value which is the date given with currentDate - 1 day.
Essentially, check if future date is given, (future date includes current day).
Hope this is clear enough. My example doesn't work and I don't understand why.
Looks like you're using format instead of parse. isBefore accepts a number or Date not a string as its first argument.
See example:
function compareDate(value: string) {
return isBefore(
parse(value, 'dd-MM-yyyy', new Date()),
sub(new Date(), { days: 1 })
);
}
const test = compareDate('31-12-2020');
console.log(test);
As requested in comments
We can run the value against a function that replaces all / and \s to -.
function unifyDateString(value: string) {
try {
return value.split("/").join("-").split(" ").join("-");
} catch {
return value;
}
}
function compareDate(value: string) {
return isBefore(
parse(unifyDateString(value), "dd-MM-yyyy", new Date()),
sub(new Date(), { days: 1 })
);
}
const one = compareDate("31-12-2020");
const two = compareDate("31/12/2020");
const three = compareDate("31 12 2020");
console.log(one);
console.log(two);
console.log(three);

Convert date range object into ISO-8601 format using moment.js

I am using this react based date range picker. It gives me a setSelectedDayRange as an object of from and to like this
from: {day: 3, month: 8, year: 2020}
to: {day: 8, month: 8, year: 2020}
I need to convert the above into the ISO-8601 format. Since I already have moment.js installed in my project, I was hoping to utilize it.
The problem is
if I try to do it like
setSelectedDayRange = moment();
let convertedDate = moment().toISOString();
console.log("setSelectedDayRange", convertedDate);
It only converts the to date.
if I try to do it like
let convertedDate = moment(setSelectedDayRange).toISOString();
console.log("setSelectedDayRange", convertedDate);
It ends up converting currentDate-1
handleDatePickerChange = (setSelectedDayRange) => {
console.log("initializing handleDatePickerChange()");
console.log("setSelectedDayRange", setSelectedDayRange);
// TODO
// convert the dates
setSelectedDayRange = moment();
let convertedDate = moment().toISOString();
console.log("setSelectedDayRange", convertedDate);
// let convertedDate = moment(setSelectedDayRange).toISOString();
// console.log("setSelectedDayRange", convertedDate);
this.setState({
selectedDayRange: setSelectedDayRange,
});
};
Sandbox URL to mess around with it.
Ciao, if you need just to convert setSelectedDayRange to date in toISOString you could do:
let convertedDateFrom = moment(setSelectedDayRange.from).toISOString();
console.log("setSelectedDayRange", convertedDateFrom);
let convertedDateTo = moment(setSelectedDayRange.to).toISOString();
console.log("setSelectedDayRange", convertedDateTo);
Here your code modified.

convert string to UTC time using jquery

I am trying to convert string to time, the string i have are in this format, '8:3' and '16:45'.
I want to convert UTC time in jQuery.
You can write your function to create UTC date with the time string.
function toUTC(str) {
let [h, m] = str.split(':');
let date = new Date();
date.setHours(h, m, 0)
return date.toUTCString();
}
console.log(toUTC('8:3'))
console.log(toUTC('16:45'))
You don't need jQuery for such operations. Just the simple Date object will do the trick. Say you want to convert time from a specific date.
let date = new Date('2020-04-01'); // leave the Date parameter blank if today
date.setHours(16); // must be 24 hours format
date.setMinutes(45);
let theUTCFormat = date.getUTCDate();
Cheers,

Node.js date parameters

I am creating a node.js endpoint that accepts a start date/time and end date/time as parameters. I had been passing them as a string ie:
var body = {
relatedObjectId: "561ee6bbe4b0f25b4aead5c8",
startTime : "11/13/2015 03:00:00PM",
endTime: "11/13/2015 03:30:00PM"
};
and in my service class:
var timeTicket = new TimeTicket();
timeTicket.tutorId = tutorId;
timeTicket.startTime = new Date(startTime);
timeTicket.endTime = new Date(endTime);
timeTicket.save(function(err, timeTicket){
if(err){
return next(err, null);
}
return next(null, timeTicket);
});
However, the cast always fails so i end up with a date in 1970 for startTime and endTime values. It would seem the obvious solution would be to use a UTC format, but what's the right way to do that?
Either use ISO 8601 format as Phil suggested, or simply pass the date as milliseconds (since 1970).
For example, new Date(1447378736842) is the same as new Date("2015-11-13T01:38:56.842Z").
To get the current date in ISO 8601 format, you might do something like this:
var d = new Date();
var n = d.toISOString();
tl;dr version: This is what your body object should look like. I used milliseconds for startTime and an ISO 8601 string for endTime for demonstration purposes. Both are valid.
var body = {
relatedObjectId: "561ee6bbe4b0f25b4aead5c8",
startTime : 1447378736842,
endTime: "2015-11-13T01:38:56.842Z"
};

Categories

Resources