JS Date incrementation - javascript

Doing this without libraries.
dates.forEach((date) => {
if(date.getDay() == 6) {
console.log('sat', date)
var t = new Date()
console.log('sat new', new Date(t.setDate(date.getDate() + 1)))
} else ...
}
Gives this output
sat
Date Sat Jan 01 2022 00:00:00 GMT+0200 (Eastern European Standard Time)
sat new
Date Sat Apr 02 2022 19:10:27 GMT+0300 (Eastern European Summer Time)
The point of this code is to see if a date is a saturday. If so, increment it towards becoming a work day (i know it says +1 but its a wip)
The result is that the day gets incremented. However for some reason it moves the date towards being in march. I have looked around and apparently this is how you're supposed to do it, but its not doing it.
When I try console.log('sat new', t.setDate(date.getDate() + 1)) (without new Date()) I get a timestamp of 1646236273249. Which this site converts to the 16th of March. Don't know how useful this is.
I hope I gave all the important information here.

In order to increment a day to a given date:
date = new Date(date)
date.setDate(date.getDate() + 1)
console.log(date)

var t = new Date() - not passing anything to the Date constructor will make it "right now".
I think you need to pass the iterated date to the Date constructor:
dates.forEach((date) => {
if(date.getDay() == 6) {
console.log('sat', date)
var t = new Date(date) // this line
console.log('sat new', new Date(t.setDate(date.getDate() + 1)))
}
}

Related

Why does my Date subtracts one day after converting from ISO to UTC

I am creating a todo app where users are selecting from-date and to-date.
The requirement is to display the dates in the format Month Year.
On Load the dates are working as expected
const fromDate = subtractOneYearFromDate(new Date()).toISOString());
const toDate = new Date().toISOString());
function subtractOneYearFromDate(date) {
const dateCopy = new Date(date); //2022-02-13T14:00:48.945Z
dateCopy.setFullYear(dateCopy.getFullYear() - 1); //2023-02-13T14:00:48.946Z
return dateCopy;
}
However, when users are trying to change dates, it looks like the dates are one day off. Suppose I am selecting Mar 2022 from the drop down. I get e[0] only correct. So I am converting this to ISO before calling my API.
What I am trying to achieve is : 2022-03-01T16:00:00.000Z
onChange={(e) => {
console.log("e[0]", e[0]) //Tue Mar 01 2022 00:00:00 GMT+0800 (Singapore Standard Time)
console.log(JSON.stringify(e[0])) //2022-02-28T16:00:00.000Z
console.log(e[0].toUTCString()); //28 Feb 2022 16:00:00 GMT
console.log(e[0].toISOString()); //2022-02-28T16:00:00.000Z
console.log(moment.utc(e[0]).local().toISOString()) //2022-02-28T16:00:00.000Z
}

Node.js date.getDate() doesn't return the correct date after change date hours

I need to increment hours to a date, but I can't get the correct date after change the hours. For example:
Change the current date
let x = new Date(); // 2018-05-30T00:17:04.888Z
x.setHours(x.getHours() + 24); // 2018-05-31T00:17:04.888Z
Great! Now the date should be 2018-05-31, right?
But if I try to do the following:
x.getDate();
It still returns old date: 2018-05-30 and the same happens for x.getHours()
Is there a way to handle that?
It seems to work just fine.
var date = new Date()
date
>Wed May 30 2018 03:26:19 GMT+0000 (UTC)
date.setHours( (date.getHours() + 23) )
>1527726379425
date
>Thu May 31 2018 00:26:19 GMT+0000 (UTC)
date.getDate()
>31

JS Check if multiple dates are within range

I have the following code where I have an arrival date and departure date and edit their format, as well as a disabled date:
var aankomstDatum = "19-05-2018";
var parts = aankomstDatum.split('-');
aankomstDatumDate = new Date(parts[2],parts[1]-1,parts[0]);
vertrekDatum = "02-06-2018";
var parts2 = vertrekDatum.split('-');
vertrekDatumDate = new Date(parts2[2],parts2[1]-1,parts2[0]);
var aankomstDatumDateCheck = (aankomstDatumDate.getMonth() + 1) + '/' + aankomstDatumDate.getDate() + '/' + aankomstDatumDate.getFullYear();
//alert(aankomstDatumDateCheck);
var vertrekDatumDateCheck = (vertrekDatumDate.getMonth() + 1) + '/' + vertrekDatumDate.getDate() + '/' + vertrekDatumDate.getFullYear();
//alert(vertrekDatumDateCheck);
var disabledDates = "26-05-2018";
var partsdisabled = disabledDates.split('-');
var disableddatesDatumDate = new Date(partsdisabled[2], partsdisabled[1]-1, partsdisabled[0]); //alert(disableddatesDatumDate);
var disableddatesDatumDateCheck = (disableddatesDatumDate.getMonth() + 1) + '/' + disableddatesDatumDate.getDate() + '/' + disableddatesDatumDate.getFullYear();
//alert(disableddatesDatumDateCheck);
if(dateCheck(aankomstDatumDateCheck,vertrekDatumDateCheck,disableddatesDatumDateCheck)) {
console.log("Not available");
} else {
console.log("Available");
}
function dateCheck() {
return true;
}
Basically, if the disabled date is between the arrival date and departure date, the if-else fires, and in the other case the else.
This code works (hooray!), but I'm not there yet. Because I planned to have multiple dates as var disabledDates and that's where I'm stuck. So, how can edit the code that multiple disabled dates are checked?
Here's a simplified version of your code, which works as you ask. I think it's better to construct Date objects using ISO8601 formatted text while testing i.e. "2018-05-19" (which creates dates in UTC). Also see tips at the end of the answer.
Click the Run code snippet button below the code to see the console output (much better than using alert):
var start = new Date("2018-05-19");
var end = new Date("2018-06-02");
var bookings = [
new Date("2018-05-26"),
new Date("2018-05-28")
];
if (validPeriod(start, end, bookings)) {
console.log("no bookings found");
} else {
console.log("found at least one booking");
}
function validPeriod(start, end, bookings) {
var valid = true;
for (var i = 0; i < bookings.length; i++) {
var date = bookings[i];
if (start <= date && date <= end) {
valid = false;
break;
}
}
return valid;
}
Tips
I strongly recommend you use Moment.js to work with dates. It'll save you headaches in the future.
If you don't opt for Moment.js, just remember that depending on how you create the date will depend on which timezone is used, and depending on the timezone of your computer which date will display, One easy way is to use the new Date(year, month, day, hours, minutes, seconds) constructor:
// for a browser/computer in timezone GMT+0200 (Paris)
// create a local date
new Date(2018, 5-1, 18).toString() // "Fri May 18 2018 00:00:00 GMT+0200 (CEST)"
new Date(2018, 5-1, 18).toISOString() // "2018-05-17T22:00:00.000Z"
// create a UTC date
new Date(Date.UTC(2018, 5-1, 18)).toString() // "Fri May 18 2018 02:00:00 GMT+0200 (CEST)"
new Date(Date.UTC(2018, 5-1, 18)).toISOString() // "2018-05-18T00:00:00.000Z"
// for a browser/computer in timezone GMT-0400 (New York)
// create a local date
new Date(2018, 5-1, 18).toString() // "Fri May 18 2018 00:00:00 GMT-0400 (EDT)"
new Date(2018, 5-1, 18).toISOString() // "2018-05-18T04:00:00.000Z"
// create a UTC date
new Date(Date.UTC(2018, 5-1, 18)).toString() // "Thu May 17 2018 20:00:00 GMT-0400 (EDT)"
new Date(Date.UTC(2018, 5-1, 18)).toISOString() // "2018-05-18T00:00:00.000Z"
But watch out if you use a string for the Date constructor because it uses Date.parse(dateString) internally and sometimes it's interpreted as a local date, and sometimes UTC:
// for a browser/computer in timezone GMT-0400 (New York)
new Date("08-19-2018"); // Sun Aug 19 2018 00:00:00 GMT-0400 (EDT) <-- local
new Date("08/19/2018"); // Sun Aug 19 2018 00:00:00 GMT-0400 (EDT) <-- local
new Date("2018-05-19"); // Fri May 18 2018 20:00:00 GMT-0400 (EDT) <-- UTC
new Date("2018/05/19"); // Sat May 19 2018 00:00:00 GMT-0400 (EDT) <-- local
Adding to the #djdavemark's answer,
You can also use JavaScript's in build some function to check if any date is falling in the given range.
As #RobG mentioned that for some browsers these date strings might give wrong results, therefore just to be safe you can explicitly format in the way Date constructor accepts.
From #CMS's answer Question: Why does Date.parse give incorrect results?
function parseDate(input) {
var parts = input.split('-');
// new Date(year, month [, day [, hours[, minutes[, seconds[, ms]]]]])
return new Date(parts[2], parts[1]-1, parts[0]); // Note: months are 0-based
}
var startData = parseDate("19-05-2018")
var endDate = parseDate("25-05-2018")
var dateSet = [
"20-05-2018",
"21-05-2018",
"22-05-2018"
];
var dateSet2 = [
"26-05-2018",
];
function inBetween(element, index, array) {
return parseDate(element) >= startData && parseDate(element) <= endDate;
}
console.log(dateSet.some(inBetween))
console.log(dateSet2.some(inBetween))
This looks more elegant.
For more information on array's some method MDN Docs

javascript similar Date objects, return defferent epochs?

when i use different Date constructors i receive similar Date objects but when i get there epoch values they have slightly different values.
Is it a bug or something or i'm just passing wrong value formats into constructors?
> date1 = new Date();
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date2 = new Date(date1.toString());
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date3 = new Date(date1.toISOString());
Sun Oct 04 2015 15:31:33 GMT+0330 (IRST)
> date1.getTime();
1443960093117
> date2.getTime();
1443960093000
> date3.getTime();
1443960093117
I'm using node(v0.12.2) in Ubuntu 14.04.1.
Apparently date1.toString() does not take the milliseconds into account while date1.toISOString() does. Yes, this is not a bug, you're just passing different strings. For me:
var date1 = new Date();
console.log(date1.toString(), date1.toISOString())
// Sun Oct 04 2015 14:54:37 GMT+0200
// 2015-10-04T12:54:37.113Z
The ISO date format includes a field to represent a fractional part of a second. The default date format doesn't, and when a default date format is parsed the system assumes the second value is exact.
> new Date().toString()
'Sun Oct 04 2015 07:53:48 GMT-0500 (CDT)'
> new Date().toISOString()
'2015-10-04T12:53:58.769Z'
In the ISO string, .769 is the seconds fraction part.
When you just log a date it automatically uses the default method .toString() version which drops the milliseconds. Using the below code you can see that the .###Z is dropped for .toString() but not for .toISOString() because it is in the extended ISO format.
var date1 = new Date();
var date2 = new Date(date1.toString());
var date3 = new Date(date1.toISOString());
console.log('date1 ' + date1.toISOString());
console.log('date2 ' + date2.toISOString());
console.log('date3 ' + date3.toISOString());
console.log('date1 ' + date1.getTime());
console.log('date2 ' + date2.getTime());
console.log('date3 ' + date3.getTime());
Which returns
date1 2015-10-04T13:34:37.778Z
date2 2015-10-04T13:34:37.000Z
date3 2015-10-04T13:34:37.778Z
date1 1443965677778
date2 1443965677000
date3 1443965677778
Hopefully this helps.

Format date time JavaScript

How to format date and time like this in JavaScript ?
March 05, 2012 # 14:30 (UTC - 9:30)
I use this code to calculate EST time :
function getDate() {
var now = new Date();
var utc = now.getTime() + (now.getTimezoneOffset() * 60000);
return new Date(utc + (3600000 * -4));
}
I use the date-time-format that Tats recommended because doing it manually is a huge PIA.
var yourDate = dateFormat(getDate(), "mmmm dd, yyyy # HH:MM) + "(UTC -9:30)";
Keep in mind this isn't Daylight Savings aware.. and you are asking for UTC -9:30 in your format, but your function converts to -4. Also, I believe that now.getTime returns in UTC.. so you can just add your difference there.
JavaScript Date Format
Check out date.js! It's a really powerful little library for working with Dates in JavaScript.
To get today's date in EST, you can do something like...
var today = new Date();
today.toString(); // outputs "Wed Apr 11 2012 15:40:40 GMT-0500 (CDT)"
today.setTimezone("EST");
today.toString(); // outputs "Wed Apr 11 2012 14:40:40 GMT-0500 (CDT)"
Also, its worth mentioning to checkout moment.js. I think the two libraries complement each other.
If you do just
var now = new Date();
document.write(now);
you will get
Wed Mar 14 2012 20:53:06 GMT+0000 (GMT Standard Time)
Link1, Link2.
Is it what you want?

Categories