I'm currently working on a MERN stack application and it's hosted through AWS EC2.
So when I try to get the current date/time using Node, I get the server's date and time.
How can I get the current time of a specific country/timezone on the server?
There are couple of options you have.
If you follow the 1st option you can get the server UTC time using a HTTP request.
For the 2nd option, you need to calculate the time for New Zealand using JavaScript in client's browser.
// create Date object for current location
var date = new Date();
// convert to milliseconds, add local time zone offset and get UTC time in milliseconds
var utcTime = date.getTime() + (date.getTimezoneOffset() * 60000);
// time offset for New Zealand is +12
var timeOffset = 12;
// create new Date object for a different timezone using supplied its GMT offset.
var NewZealandTime = new Date(utcTime + (3600000 * timeOffset));
Note: This won't reflect Daylight Saving Time.
Use a third party api to show time from a specific country. You can use api from worldtimeapi.org/. Make an ajax call, get the time of your desired location. You can use plain javascript or use any ajax library to do that. Here I'm including two methods: 1) plain javascript and 2) using axios
VANILLA JS
function getTime(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open("GET", url);
req.onload = () =>
req.status === 200
? resolve(req.response)
: reject(Error(req.statusText));
req.onerror = (e) => reject(Error(`Network Error: ${e}`));
req.send();
});
}
Now Use this function to make the ajax call
let url = "http://worldtimeapi.org/api/timezone/Pacific/Auckland";
getTime(url)
.then((response) => {
let dateObj = JSON.parse(response);
let dateTime = dateObj.datetime;
console.log(dateObj);
console.log(dateTime);
})
.catch((err) => {
console.log(err);
});
AXIOS
axios({
url:"http://worldtimeapi.org/api/timezone/Pacific/Auckland",
method: "get",
})
.then((response) => {
let dateObj = response.data;
let dateTime = dateObj.datetime;
console.log(dateObj);
console.log(dateTime);
})
.catch((err) => {
console.log(err);
});
Hope that helps. Bear one thing in mind though, worldtimeapi.org/ is a third party service. If they choose to terminate their service, your code will break. Happy coding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With