2
votes

Below is my code:

var date = new Date().toLocaleString("en-US", { timeZone: "Asia/Kolkata" });
var n = date.getDay();

Trying to convert data into IST.

without .toLocaleString .getday is working perfectly. But when used getting below error:

TypeError: date.getDay is not a function
    at Object. (D:\Learning\node-course\web-server\src\app.js:12:14)
    at Module._compile (internal/modules/cjs/loader.js:1200`enter code here`:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1220:10)
    at Module.load (internal/modules/cjs/loader.js:1049:32)
    at Function.Module._load (internal/modules/cjs/loader.js:937:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
    at internal/main/run_main_module.js:17:47

Is there any better way to convert date into IST and find the day as well?

2

2 Answers

0
votes

The return value from toLocaleString is a string. Strings don't have a getDay method.

JavaScript's Date object has no features letting you use other timezones. It only supports UTC and the current timezone where the code is running (simultaneously, by offering some methods that give you information in UTC and others that give you information in your local timezone). (There's a proposal that will fix that, but it's still only at Stage 2.)

If you want to know what day it is in the user's current timezone, just use getDay directly on your date object. If you want a different timezone, you'll need a well-maintained library that supports multiple timezones.

0
votes

Because its converted in to string, and string don't have getDay() function, You can try,

var dateString = new Date().toLocaleString("en-US", { timeZone: "Asia/Kolkata" });
var date = new Date(dateString);
var n = date.getDay();

console.log("Date String: ", dateString);
console.log("Day:", n);