How to set server time in Node.js - javascript

I would like to set (mock) my custom time to the Node.js server for testing purposes. Something like this:
console.log(new Date());
// Sat Jun 30 2018 20:00:00 GMT+0100
// ^^
someFunctionToSetTime('Sat Jun 30 2018 12:00:00 GMT+0100')
// ^^
console.log(new Date());
// Sat Jun 30 2018 12:00:00 GMT+0100
// ^^
How do I do this?
P.S. I don't really want to fake the Date class.

Just monkey patch the Date constructor:
let now = 'Sat Jun 30 2018 12:00:00 GMT+0100';
{
const oldDate = Date;
Date = function(...args) {
if(args.length) {
return new oldDate(...args);
} else {
return new oldDate(now);
}
};
Date.parse = oldDate.parse;
Date.UTC = oldDate.UTC;
Date.now = () => +(new Date());
}

First option : Without external modules you can use this to get timezone Date and time in node.js
var myDate = new Date().toLocaleString('en-US', {
timeZone: 'Europe/Paris'
});
Second option : Use momentjs timezone witch allows you to set your location and more... just check the documentation.

Related

Having issue calculating timeSince due to timeZone confusion

So I am a little bit confused. the server return date is in UTC ISO format, my local time is CST.
so I use toLocaleString() and then subtract the difference but I get a negative number. I rather use react native library rather than installing new libraries such as moment
export function timeSince(date) {
//date is 2022-11-07T18:36:39.543 which is UTC, not CST
date = date.toLocaleString("en-US", {
timeZone: "CST",
});
// somehow stayed 2022-11-07T18:36:39.543
date = new Date(date);
//Mon Nov 07 2022 18:36:39 GMT-0600 (Central Standard Time)
Mon Nov 07 2022 12:29:21 GMT-0600 (Central Standard Time)
'2022-11-07T18:27:38.03'
var seconds = Math.floor((new Date() - date) / 1000); // -21506
return seconds
}

Javascript Date comparison coming from server and new Date()

I have a date coming from database which is 2022-10-31 11:33:07.861Z, and in my js file I have this date is saved in a variable :
function test() {
let now = new Date().toLocaleString('en-GB', { timeZone: 'Europe/London'}); // I need now to be Europe/london time
let dateFromDb = db_date; // 2022-10-31 11:33:07.861Z
// I have a function which takes ^ above date and returns this : Mon Oct 31 2022 11:33:07 GMT+0000 (Greenwich Mean Time)
let formatedDate= this.toDate(dateFomDb); // returns : Mon Oct 31 2022 11:33:07 GMT+0000 (Greenwich Mean Time)
}
When I console.log(now, typeOf now) I get this: 02/11/2022, 23:24:52 string
and console for formatedDate returns this : Mon Oct 31 2022 11:33:07 GMT+0000 Object
I need to compare both dates :
return newDate <= now; // expect it to true or false;
Can anyone please suggest me how can I do this ?
I tried to cast both dates toLocalString but its string from I need object.

Convert Javascript Date object to other timezone Date Object

How to convert Javascript Date Object to another timezone but the result must be Date object with the correct timezone
let date = new Date();
console.log(date);
date = date.toLocaleString('en-US', { timeZone: 'America/Vancouver' });
date = new Date(date);
console.log(date);
that gives the following result, the last result line (Date/Time) is correct but the time zone is incorrect which is still GMT-0500 (Colombia Standard Time) but must be GMT-0800 (Pacific Standard Time) timezone
Wed Jan 20 2021 00:14:11 GMT-0500 (Colombia Standard Time)
Tue Jan 19 2021 21:14:11 GMT-0500 (Colombia Standard Time)
You may try this :
let date = new Date();
console.log(date);
date = date.toLocaleString("en-CA", {
timeZone: "America/Vancouver",
timeZoneName: "long",
});
console.log(date);
Output:
Wed Jan 20 2021 09:18:16 GMT+0300 (Arabian Standard Time)
2021-01-19, 10:18:16 p.m. Pacific Standard Time
Once you get the correct TimeZone, you may change how the date and time are displayed by string manipulation if you need too.
Update:
This may not look pretty but i believe it should satisfy the requirements:
let date = new Date().toLocaleString("en-US", {
timeZone: "America/Vancouver",
timeZoneName: "short",
});
let date1 = new Date(date);
//adding a new property to Date object called tz and initializing it to null
Date.prototype.tz = null;
//stting the tz value to the Time zone output from toLocalString
date1.tz = date.slice(date.length - 3);
console.log(date1.toISOString() + " " + date1.tz);
console.log(date);
console.log(typeof date1);
Output:
2021-01-20T09:01:06.000Z PST
1/20/2021, 1:01:06 AM PST
Object
What i've done is create a new property of the object date to replace the built-in time zone property in Date, hence you get an object with a user specified Time zone.

Let value changes out of nowhere

Can someone please explain to me, why start and end variables print to console different values for these loggers?
I get printed out:
start1 = Mon Feb 17 2020 10:00:00 GMT+0100 (Central European Standard Time)
end1 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
start2 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
end2 = Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time)
I want to add, that the code I presented is in some method of course, and the names start and end don't interfere with other variable names.
let start = this.service.getDateTime(
eventFromUi.start_date,
eventFromUi.start_time_hour,
eventFromUi.start_time_minute
);
console.log("start1 = " + start);
let end = this.service.getDateTime(
eventFromUi.start_date,
eventFromUi.end_time_hour,
eventFromUi.end_time_minute
);
console.log("end1 = " + end);
console.log("start2 = " + start);
console.log("end2 = " + end);
EDIT:
The getDateTime() method returns object of TypeScript ootb type Date.
I used Chrome debugger to look into this, and I see that when I first execute the getDateTime() method, I get value Mon Feb 17 2020 10:00:00 GMT+0100 (Central European Standard Time) returned and assigned to let start.
Then the method getDateTime() is executed again and retuns value Mon Feb 17 2020 11:30:00 GMT+0100 (Central European Standard Time), and this value gets assigned to both start and end variables.
How does this happen?
EDIT2:
Function getDateTime:
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = dateWithoutTime;
console.log(date);
console.log(hour);
console.log(minute);
date.setHours(hour);
date.setMinutes(minute);
return date;
}
This is happening because you're dealing with object references.
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = dateWithoutTime;
// date is now a copy of the *reference* to the same object that
// dateWithoutTime is a reference to. In other words: it is pointing
// to the same object in memory
date.setHours(hour);
date.setMinutes(minute);
// since date is pointing to the same object as dateWithoutTime, this is
// modifying both date and dateWithoutTime
return date;
}
This also means that in your code, eventFromUi.start_date, start and end are all references pointing to the same Date object.
To solve your problem, make sure you create a clone of dateWithoutTime when it is passed into your function:
getDateTime(dateWithoutTime: Date, hour: number, minute: number): Date {
let date = new Date(dateWithoutTime);
// date is now a reference to a *new Date object* with the same
// date/time/etc. values as dateWithoutTime
date.setHours(hour);
date.setMinutes(minute);
// since date now points to a new object, this is only modifying date
// while leaving dateWithoutTime alone and unchanged
return date;
}

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

Categories