Convert milliseconds into date in different timezones - javascript

How to convert milliseconds in mm/dd/yyyy in different timezones.
I have a datepicker, when I press save, it saves the date in millisecond.
The saved millisecond should display date according to timezone date.
My Code:
var millisecond=1378792800000;
var date=new Date(millisecond);
var date_month = date.getMonth() + 1;
display_date = date_month + "/" + date.getDate() + "/" + date.getFullYear();
The date is differ in different timezones
When my timezone is India GMT then it is 09/10/2013
and when I change my timezone to US Mountain it change to 09/09/2013.
So how can I handle different timezone in javascript.

I would suggest using a third party script such as moment.js to make your life easier
Here is an example: http://jsfiddle.net/cyxgJ/
var ms = 1378792800000;
var date = new moment(ms);
// see <http://momentjs.com/docs/#/manipulating/timezone-offset/>
date = date.zone(120);
document.body.innerHTML = date;

Related

Get UTC Time Information (Need People to Test my Snippet)

I have created a small snippet, which is supposed to return the UTC time value for the user's country based on their computer settings. However, I would be really thankful if you can test the snippet and give me some feedback if it managed to display the correct UTC value for your country. Any feedback would be high appreciated. Thank you in advance.
PS: What I learned from Wikipedia while researching how to tackle this problem is that UTC is not a time zone, therefore the 1 hour change in some countries between the winter and summer time would not affect the UTC value. However, please note that UTC is equal to GMT (Winter time) therefore for the countries which are using the summer time as of writing this post an hour has to be extracted to get the GMT (Winter Time), which in theory has to be equal to the UTC value.
var currentDate = new Date();
var fetchYear = currentDate.getFullYear();
var fetchMonth = currentDate.getMonth();
var fetchDay = currentDate.getDate();
var fetchHour = currentDate.getHours();
var fetchMinutes = currentDate.getMinutes();
var fetchSeconds = currentDate.getSeconds();
var fetchMilliseconds = currentDate.getMilliseconds();
var referenceDate = new Date(fetchYear, 0, fetchDay, fetchHour, fetchMinutes, fetchSeconds, fetchMilliseconds)
var currentDateToString = currentDate.toString().match(/[+|-].{4}/).toString();
var referenceDateToString = referenceDate.toString().match(/[+|-].{4}/).toString();
if (currentDateToString == referenceDateToString){
document.getElementById("utcValue").innerHTML = "Output: UTC " + currentDateToString;
} else {
document.getElementById("utcValue").innerHTML = "Output: UTC " + referenceDateToString;
}
<div id="utcValue"></div>

Timezone issue converting date to "Today", "Yesterday", "2 days ago", etc. in Javascript

I have a news feed and I want to display the time an article is published simply as Today, Yesterday, 2 days, 3 days ago, etc. I just want to preserve the YYYY-MM-DD format and get rid of the timezone part. However at 8pm NYC Eastern Time (ET) the dates change for example from 2 days ago to 3 days ago. How can I make sure that this change is only made at midnight ET every day?
An example of an article date:
2020-03-17T04:00:00.000Z
Current code:
convertDateLiteral(article_date: string) {
const newDt = article_date.split('T')[0];
let date = moment(newDt);
if (moment({hours: 0}).diff(date, 'days') >= 2) {
return date.add(1,'d').fromNow(); // '2 days ago' etc.
}
//console.log(date.calendar().split(' ')[0])
return date.calendar().split(' ')[0]
}
Given dates strings in ISO 8601 format, you can convert to Date objects, zero the time, then compare to today's date with zeroed time and rounding for daylight saving changes, if any. E.g.
function getEvenDaysDiff(d) {
let now = new Date();
now.setHours(0,0,0,0);
let then = new Date(d);
then.setHours(0,0,0,0);
return Math.round((now - then) / 8.64e7);
}
function parseAndFormatDate(d) {
d = new Date(d);
let z = n => (n<10?'0':'')+n;
return d.getFullYear() + '-' +
z(d.getMonth()+1) + '-' +
z(d.getDate());
}
// test - dates are UTC so local dates may differ
let dates = [
'2020-03-17T04:00:00.000Z',
'2020-03-16T14:00:00.000Z',
'2020-03-12T04:30:00.000Z',
'2020-02-17T12:00:00.000Z'
].forEach(
s => console.log(parseAndFormatDate(s) + ' ' + getEvenDaysDiff(s) + ' days ago.')
);
Note that as the timestamps are UTC, the date they represent may be different to the equivalent local date. I've assumed you want differences to local dates. If you want UTC, then use UTC methods in getEvenDaysDiff and the parseAndFormatDate function is superfluous.

Determining DST or CST timezone from UTC timezone

I have UTC timeZone Date which I want to convert CST or DST based on whether DST is applied in the same city or not.
Since my browser is not based on same city so local time is no use of it.
example: my user is based on India but they will see data for NewYork Date also
I have a server based on NewYork so using SSR I can get date of the server but its always showing in CST how I can change the date into DST?
try this code. it might help you.
let d = new Date()
let utc = d.getTime() + (d.getTimezoneOffset() * 60000)
let today = new Date(utc - (3600000 * 6)) // 6 is for cst timezone. we can change this to get other timezome . this is offset
let dd = today.getDate()
let mm = today.getMonth()+1
let yy = today.getFullYear()
let hh = today.getHours()
let i = today.getMinutes()
let sec = today.getSeconds()
hh = hh.toString().length<2?("0"+hh):hh
mm = mm.toString().length<2?("0"+mm):mm
i = i.toString().length<2?"0"+i:i
sec = sec.toString().length<2?"0"+sec:sec
let timestamp = dd+'/'+mm+'/'+yy+' '+hh+':'+i+':'+sec
console.log('timestamp ',timestamp)
You can use Date.toLocaleString() to convert a UTC date to a specific timezone. This will honour the local DST rules and is native JavaScript code (no libraries required!)
So, if we have a list of UTC dates, we can convert to a specific timezone. I've created a list of UTC dates and timezones and formatted the dates for that timezone and date.
You can select a different display locale of course, for example if you have Indian clients you could use "en-in" or whichever you decide is the best display locale.
You should be able to do any timezone conversion either on the server side or (preferably) on the client side. If you send all dates to the client in UTC format (e.g. YYYY-MM-DDTHH:mm:ssZ) you can convert to the client timezone in the client code.
const displayLocale = "en-us"; // Set this to en-gb, en-in etc..
const uctDateList = [ new Date("2019-06-01T12:00:00Z"), new Date("2019-12-01T12:00:00Z")];
const timeZoneList = ['America/New_York', 'America/Los_Angeles', 'Asia/Kolkata'];
uctDateList.forEach(utcDate => {
console.log("\nServer Time: ", utcDate.toISOString());
timeZoneList.forEach(timeZone => {
console.log(`Time in timezone (${timeZone}):`, utcDate.toLocaleString(displayLocale, { timeZone }));
})
});

Comparing time from different timezones with moment.js

I have a Node.js server that triggers function based on timezones. Specifically, I'm using moment-timezone and from a fixed date and time input I need to trigger action at that same input but in different time zones.
So if I set in my server that the action should be triggered at 1:00 pm UK time and the user is in New York, I want the action to be triggered at 1:00 pm in New York.
That's what I am doing now:
exports.time_to_trigger = function(hour, date) {
var user_timezone = "Asia/Tokyo";
// create date object from date + hour strings
var dateObj = moment(date + hour, process.env.DATE_FORMAT + " HH:mm a");
// create offset
var max_value = moment(dateObj).add(3, 'minutes');
var low_value = moment(dateObj).add(-3, 'minutes');
console.log(max_value); // -> moment("2018-01-25T13:03:00.000")
console.log(low_value); // -> moment("2018-01-25T12:57:00.000")
// get the now value of the user timezone
var user_now = moment.tz(moment(), user_timezone);
console.log(user_now); // -> moment.parseZone("2018-01-24T13:01:00.038+09:00")
console.log(user_now.isAfter(low_value)); // -> false
console.log(user_now.isBefore(max_value)); // -> true
return (
user_now.isAfter(low_value) &&
user_now.isBefore(max_value)
)
}
As you can see from the comment, this is not working as the comparison with isAfter and isBefore take into consideration the time zone that I converted on purpose not to have this problem. How can I solve this?
Your issue is that you use timezone to get user_now but not to create dateObj. So dateObj is missing the timezone offset and your 2 dates are not comparable as you would wish.
To have all your dates on the same timezone:
// create date object from date + hour strings
var dateObj = moment.tz(date + hour, process.env.DATE_FORMAT + " HH:mm a", user_timezone);

UTC Times in JavaScript

I am trying to get the current UTC date to store in my database. My local time is 9:11 p.m. This equates to 1:11 a.m. UTC. When I look in my database, I notice that 1:11 p.m. is getting written to. I'm confused. In order to get the UTC time in JavaScript, I'm using the following code:
var currentDate = new Date();
var utcDate = Date.UTC(currentDate.getFullYear(), currentDate.getMonth(), currentDate.getDate(), currentDate.getHours(), currentDate.getMinutes(), currentDate.getSeconds(), currentDate.getMilliseconds());
var result = new Date(utcDate);
What am I doing wrong?
A lttle searching turned out you can do this:
var now = new Date(),
utcDate = new Date(
now.getUTCFullYear(),
now.getUTCMonth(),
now.getUTCDate(),
now.getUTCHours(),
now.getUTCMinutes(),
now.getUTCSeconds()
);
Even shorter:
var utcDate = new Date(new Date().toUTCString().substr(0, 25));
How do you convert a JavaScript date to UTC?
It is a commonly used way, instead of creating a ISO8601 string, to get date and time of UTC out. Because if you use a string, then you'll not be able to use every single native methods of Date(), and some people might use regex for that, which is slower than native ways.
But if you are storing it in some kind of database like localstorage, a ISO8601 string is recommended because it can also save timezone offsets, but in your case every date is turned into UTC, so timezone really does not matter.
If you want the UTC time of a local date object, use the UTC methods to get it. All javascript date objects are local dates.
var date = new Date(); // date object in local timezone
If you want the UTC time, you can try the implementation dependent toUTCString method:
var UTCstring = date.toUTCString();
but I wouldn't trust that. If you want an ISO8601 string (which most databases want) in UTC time then:
var isoDate = date.getUTCFullYear() + '-' +
addZ((date.getUTCMonth()) + 1) + '-' +
addZ(date.getUTCDate()) + 'T' +
addZ(date.getUTCHours()) + ':' +
addZ(date.getUTCMinutes()) + ':' +
addZ(date.getUTCSeconds()) + 'Z';
where the addZ function is:
function addZ(n) {
return (n<10? '0' : '') + n;
}
Modify to suit.
Edit
To adjust a local date object to display the same time as UTC, just add the timezone offset:
function adjustToUTC(d) {
d.setMinutes(d.getMinutes() + d.getTimezoneOffset());
return d;
}
alert(adjustToUTC(new Date())); // shows UTC time but will display local offset
Take care with the above. If you are say UTC+5hrs, then it will return a date object 5 hours earlier but still show "UTC+5"
A function to convert a UTC ISO8601 string to a local date object:
function fromUTCISOString(s) {
var b = s.split(/[-T:\.Z]/i);
var n= new Date(Date.UTC(b[0],b[1]-1,b[2],b[3],b[4],b[5]));
return n;
}
alert(fromUTCISOString('2012-05-21T14:32:12Z')); // local time displayed
var now = new Date();
var utc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);

Categories