Date Code will only work in chrome - javascript

The problem is that this program will only work in Chrome, no matter what date format I use or when I parsed the dates using , it would return NaN.
The program converts the two dates (constant and a certain holiday) into milliseconds from Jan 1st, 1970. The dates are compared and subtracted. Then they are divided and rounded into seconds until the date. The problem, I believe lies when the dates are set. I do NOT want to mess with timezones.
jQuery in the answer is fine. Regex's are fine, but I don't understand them.
If the answer could have a working proof, that would be cool. Thanks!
The html is (all that matters)
<p id="output">
</p>
The code is
$(document).ready(function() {
var date = new Date();
var year = date.getFullYear();
console.log(year + "-12-25");
var christmasdate = new Date(year + "-12-24 24:00:00");
$("#output").css("font-size","20px");
$("#output").html("If this lasts more than a second, something is wrong.");
setInterval(function() {
date = new Date();
var curr_time = date.getTime();
var xmas_time = christmasdate.getTime();
var time_left = Math.round((xmas_time - curr_time) / 1000);
var output;
if (time_left < 0) {
output = "Christmas was " + Math.abs(time_left) + " seconds ago."
}
else {
output = "There is " + time_left + " seconds until christmas eve.";
}
if (time_left == 1) {
output = "There is " + time_left + "second until christmas eve.";
}
$("#output").html(output);
var bodyheight = $(document).height();
var allheight = $("body").height();
$("h2").css("margin-top",(bodyheight / 2) - (allheight / 2))
}, 1000);
});
The link is http://jsbin.com/suyedol/5/edit.

From MDN:
Because of the variances in parsing of date strings, it is recommended to always manually parse strings as results are inconsistent, especially across different ECMAScript implementations where strings like "2015-10-12 12:00:00" may be parsed to as NaN, UTC or local timezone.
But instead of
var christmasdate = new Date(year + "-12-24 24:00:00");
You could instead use:
var christmasdate = new Date(year,11,24,24,0,0);
Which Safari computed as
Mon Dec 25 2017 00:00:00 GMT-0500 (EST)

Your computation of christmas in the current year seems overly complex and error prone. You certainly should not be using the Date constructor to parse strings (or Date.parse, they are equivalent for parsing).
Consider the following, which creates a date for 00:00:00 on Christmas morning in the current year.
var christmas = new Date();
christmas.setHours(0,0,0,0);
christmas.setMonth(11,25);
console.log(christmas.toString());

Related

Add one day to date in javascript

I am sure that a lot of people asked this question but when I checked the answers it seems to me that they are wrong that what I found
var startDate = new Date(Date.parse(startdate));
//The start date is right lets say it is 'Mon Jun 30 2014 00:00:00'
var endDate = new Date(startDate.getDate() + 1);
// the enddate in the console will be 'Wed Dec 31 1969 18:00:00' and that's wrong it should be 1 july
I know that .getDate() return from 1-31 but Does the browser or the javascript increase only the day without updating the month and the year ?
and in this case Should I write an algorithm to handle this ? or there is another way ?
Note that Date.getDate only returns the day of the month. You can add a day by calling Date.setDate and appending 1.
// Create new Date instance
var date = new Date()
// Add a day
date.setDate(date.getDate() + 1)
JavaScript will automatically update the month and year for you.
EDIT:
Here's a link to a page where you can find all the cool stuff about the built-in Date object, and see what's possible: Date.
The Date constructor that takes a single number is expecting the number of milliseconds since December 31st, 1969.
Date.getDate() returns the day index for the current date object. In your example, the day is 30. The final expression is 31, therefore it's returning 31 milliseconds after December 31st, 1969.
A simple solution using your existing approach is to use Date.getTime() instead. Then, add a days worth of milliseconds instead of 1.
For example,
var dateString = 'Mon Jun 30 2014 00:00:00';
var startDate = new Date(dateString);
// seconds * minutes * hours * milliseconds = 1 day
var day = 60 * 60 * 24 * 1000;
var endDate = new Date(startDate.getTime() + day);
JSFiddle
Please note that this solution doesn't handle edge cases related to daylight savings, leap years, etc. It is always a more cost effective approach to instead, use a mature open source library like moment.js to handle everything.
There is issue of 31st and 28th Feb with getDate() I use this function getTime and 24*60*60*1000 = 86400000
Use this function:
function incrementDate(dateInput,increment) {
var dateFormatTotime = new Date(dateInput);
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
return increasedDate;
}
Example as below:
var dateWith31 = new Date("2017-08-31");
var dateWith29 = new Date("2016-02-29");
var amountToIncreaseWith = 1; //Edit this number to required input
console.log(incrementDate(dateWith31,amountToIncreaseWith));
console.log(incrementDate(dateWith29,amountToIncreaseWith));
function incrementDate(dateInput,increment) {
var dateFormatTotime = new Date(dateInput);
var increasedDate = new Date(dateFormatTotime.getTime() +(increment *86400000));
return increasedDate;
}
use this i think it is useful for you
var endDate=startDate.setDate(startDate.getDate() + 1);
I think what you are looking for is:
startDate.setDate(startDate.getDate() + 1);
Also, you can have a look at Moment.js
A javascript date library for parsing, validating, manipulating, and formatting dates.
var datatoday = new Date();
var datatodays = datatoday.setDate(new Date(datatoday).getDate() + 1);
todate = new Date(datatodays);
console.log(todate);
This will help you...
add one day in javascript in one line
NB: if you want to add a specific number of days ... just replace 1 with the number of days you want
new Date(new Date().setDate(new Date().getDate() + 1))
console.log(new Date(new Date().setDate(new Date().getDate() + 1)))
i know it's been long time since this is posted but here's my answer
function addDays(date, n)
{
const oneDayInMs = 86400 * 1000;
return new Date(Date.parse(date) + (n * oneDayInMs));
}
addDays(new Date(), 1);
Just for the sake of adding functions to the Date prototype:
In a mutable fashion / style:
Date.prototype.addDays = function(n) {
this.setDate(this.getDate() + n);
};
// Can call it tomorrow if you want
Date.prototype.nextDay = function() {
this.addDays(1);
};
Date.prototype.addMonths = function(n) {
this.setMonth(this.getMonth() + n);
};
Date.prototype.addYears = function(n) {
this.setFullYear(this.getFullYear() + n);
}
// etc...
var currentDate = new Date();
currentDate.nextDay();
If you don't mind using a library, DateJS (https://github.com/abritinthebay/datejs/) would make this fairly easy. You would probably be better off with one of the answers using vanilla JavaScript however, unless you're going to take advantage of some other DateJS features like parsing of unusually-formatted dates.
If you're using DateJS a line like this should do the trick:
Date.parse(startdate).add(1).days();
You could also use MomentJS which has similar features (http://momentjs.com/), however I'm not as familiar with it.
The below will add a single day to a current time. I believe this will handle daylight saving times, etc.
function increment_date (date) {
let old_date = new Date (date);
date.setDate (old_date.getDate() + 1);
while (date.getDate() == old_date.getDate()) {
date.setHours (date.getHours() + 1);
}
date.setHours (0);
}

JavaScript New Date from a 12 hour format date and time string

Example string: 2014-12-31 11:59 pm
As it stands, JavaScript isn't even parsing the time as the resulting time code returns 12:00 am regardless of what time I provide.
Output after new Date("2014-12-31 11:59 pm") results in: 2014-12-31 12:00 am
EDIT:
Even after expecting a format and manually parsing the string, the new Date() constructor isn't behaving...
var sourceTime = "2014-12-31 11:59 pm";
var dateRaw = sourceTime.split(' ');
var dateYMD = dateRaw[0].split('-');
var dateTime = dateRaw[1].split(':');
var dateAmPm = dateRaw[2].toLowerCase();
// Adjust human month to system month...
dateYMD[1] = (parseInt(dateYMD[1]) - 1).toString();
// Convert 12h to 24h...
if(dateAmPm == 'pm') {
if(parseInt(dateTime[0]) < 12) dateTime[0] = (parseInt(dateTime[0])+12).toString();
} else {
if(parseInt(dateTime[0]) == 12) dateTime[0] = 0;
}
console.log(dateYMD);
console.log(dateTime);
var dateParsed = new Date(dateYMD[0], dateYMD[1], dateYMD[2], dateTime[0], dateTime[1]);
The console log shows the correct values being passed into new Date() but I'm still getting an incorrect output :(
Instead of using the standard Date from JavaScript I always use Moment.js when working with dates. It makes is very easy to work with different formats of dates and customizing everything.
In your case you could do something like:
var datestr = "2014-12-31 11:59 pm";
var date = moment(datestr,"YYYY-MM-DD HH:mm a")
$("#log").text(date.format("HH:mm:SS MMM DD YYYY"));
Here's a jsfiddle to try it.
As far as I know, there is no possibility to change the format of the Date String parsed by the Date constructor or Date.parse() in JavaScript. Format specifications can be found at RFC822 or ECMAScript Standards, and neither does support am/pm.
(links taken from MDN)
I'm fixed my problem.. Solution..
let ThisDate = this.startDate0;
let FinalYear = ThisDate.substring(6,10);
let FinalMonth = ThisDate.substring(3,5);
let FinalDay = ThisDate.substring(0,2);
let FinalHour = ThisDate.substring(11, 13);
let FinalMinutes = ThisDate.substring(14,16);
let FinalDate = FinalYear + "-" + FinalMonth + "-" + FinalDay + " " + FinalHour + ":" + FinalMinutes;

How to add weeks to date using javascript?

Javascript definitely isn't my strongest point. I've been attempting this for a couple of hours now and seem to be getting stuck with date formatting somewhere.
I have a form where a user selected a date (dd/mm/yyyy) and then this date will be taken and 2 weeks will be added to it and then date will be copied to another form field.
My latest attempt below isn't even adding a date yet just copying the selected date in one form field to another, if I select '03/02/2012', it outputs 'Fri Mar 02 2012 00:00:00 GMT+0000 (GMT Standard Time)', so its outputting in American format as well as the full date. How to I get it to out put in the same format and add 2 weeks?
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
document.frmAccept.acceptLicence.value = date1;
}
You can do this :
const numWeeks = 2;
const now = new Date();
now.setDate(now.getDate() + numWeeks * 7);
or as a function
const addWeeksToDate = (dateObj,numberOfWeeks) => {
dateObj.setDate(dateObj.getDate()+ numberOfWeeks * 7);
return dateObj;
}
const numberOfWeeks = 2
console.log(addWeeksToDate(new Date(), 2).toISOString());
You can see the fiddle here.
According to the documentation in MDN
The setDate() method sets the day of the Date object relative to the beginning of the currently set month.
This might not answer the question per se, but one can find a solution with these formulas.
6.048e+8 = 1 week in milliseconds
Date.now() = Now in milliseconds
Date.now() + 6.048e+8 = 1 week from today
Date.now() + (6.048e+8 * 2) = 2 weeks from today
new Date( Date.now() + (6.048e+8 * 2) ) = Date Object for 2 weeks from today
You're assigning date1 to be a Date object which represents the string you pass it. What you're seeing in the acceptLicense value is the toString() representation of the date object (try alert(date1.toString()) to see this).
To output as you want, you'll have to use string concatenation and the various Date methods.
var formattedDate = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
In terms of adding 2 weeks, you should add 14 days to the current date;
date1.setDate(date.getDate() + 14);
... this will automatically handle the month increase etc.
In the end, you'll end up with;
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
N.B Months in JavaScript are 0-indexed (Jan = 0, Dec = 11), hence the +1 on the month.
Edit: To address your comment, you should construct date as follows instead, as the Date argument is supposed to be "A string representing an RFC2822 or ISO 8601 date." (see here).
var segments = acceptCompletionDate.split("/");
var date1 = new Date(segments[2], segments[1], segments[0]);
This should do what you're looking for.
function LicenceToOccupy(acceptCompletionDate)
{
var date1 = new Date(acceptCompletionDate);
date1.setDate(date1.getDate() + 14);
document.frmAccept.acceptLicence.value = date1.getDate() + '/' + (date1.getMonth() + 1) + '/' + date1.getFullYear();
}
To parse the specific dd/mm/yyyy format and increment days with 14 , you can do something like split the parts, and create the date object with y/m/d given specfically. (incrementing the days right away) Providing the separator is always -, the following should work:
function LicenceToOccupy(acceptCompletionDate)
{
var parts = acceptCompletionDate.split("/");
var date1 = new Date(parts[2], (parts[1] - 1), parseInt(parts[0]) + 14); //month 0 based, day: parse to int and increment 14 (2 weeks)
document.frmAccept.acceptLicence.value = date1.toLocaleDateString(); //if the d/m/y format is the local string, otherwise some cusom formatting needs to be done
}
date1.toLocaleDateString()
Thiswill return you date1 as a String in the client convention
To create a new date date2 with 2 weeks more (2weeks = 27246060 seconds):
var date2 = new Date(date1 + 60*60*24*7*2);

jQuery Format Time

I have a jQuery script that receives a string in milliseconds inside a parameter, like this:
params.tweetDate='77771564221';
What I need to do is to create a jQuery function that will be able to format this milliseconds string in a USA time, like 10.00 AM or 10.00 PM.
Is there a jQuery function that is able to do this?
Please help.
Thanks
There is Date object in pure javascript, no jQuery needed.
http://www.javascriptkit.com/jsref/date.shtml
Example:
var time = new Date(params.tweetDate),
h = time.getHours(), // 0-24 format
m = time.getMinutes();
// next just convert to AM/PM format (check if h > 12)
No, there's no jQuery function for this. You can use
JavaScript's own Date object, using the getHours() and getMinutes() functions, handling the AM/PM thing yourself (e.g., hours >= 12 is PM), padding out the minutes with a leading 0 if minutes is less than 10, etc. Also note that if hours is 0, you want to make it 12 (because when using the AM/PM style, you write midnight as "12:00 AM", not "0:00 AM").
DateJS, an add-on library that does a huge amount of date stuff (although sadly it's not actively maintained)
PrettyDate from John Resig (the creator of jQuery)
To use just about any of those, first you have to turn that "milliseconds" value into a Date object. If it's really a "milliseconds" value, then first you parse the string into a number via parseInt(str, 10) and then use new Date(num) to create the Date object representing that point in time. So:
var dt = new Date (parseInt(params.tweetDate, 10));
However, the value you've quoted, which you said is a milliseconds value, seems a bit odd — normally it's milliseconds since The Epoch (Jan 1, 1970), which is what JavaScript uses, but new Date(parseInt("77771564221", 10)) gives us a date in June 1972, long before Twitter. It's not seconds since The Epoch either (a fairly common Unix convention), because new Date(parseInt("77771564221", 10) * 1000) gives us a date in June 4434. So the first thing to find out is what that value actually represents, milliseconds since when. Then adjust it so it's milliseconds since The Epoch, and feed it into new Date() to get the object.
Here is a function for you:
function timeFormatter(dateTime){
var date = new Date(dateTime);
if (date.getHours()>=12){
var hour = parseInt(date.getHours()) - 12;
var amPm = "PM";
} else {
var hour = date.getHours();
var amPm = "AM";
}
var time = hour + ":" + date.getMinutes() + " " + amPm;
console.log(time);
return time;
}
You may call the function in any approach like:
var time = timeFormatter(parseInt("2345678998765"));
take a look at timeago: this is a jquery plugin used exactly for this purposes.
Using T.J.'s solution this is what I ended up with.
var date = new Date(parseInt("77771564221", 10));
var result = new Array();
result[0] = $.datepicker.formatDate('DD, M, d, yy', date);
result[1] = ' ';
if (date.getHours() > 12) {
result[2] = date.getHours() - 12;
} else if (date.getHours() == 0 ) {
result[2] = "12";
} else {
result[2] = date.getHours();
}
result[3] = ":"
result[4] = date.getMinutes();
if (date.getHours() > 12) {
result[5] = " pm";
} else {
result[5] = " am";
}
console.log(result.join(''));

How to ignore user's time zone and force Date() use specific time zone

In an JS app, I receive timestamp (eq. 1270544790922) from server (Ajax).
Basing on that timestamp I create Date object using:
var _date = new Date();
_date.setTime(1270544790922);
Now, _date decoded timestamp in current user locale time zone. I don't want that.
I would like _date to convert this timestamp to current time in city of Helsinki in Europe (disregarding current time zone of the user).
How can I do that?
A Date object's underlying value is actually in UTC. To prove this, notice that if you type new Date(0) you'll see something like: Wed Dec 31 1969 16:00:00 GMT-0800 (PST). 0 is treated as 0 in GMT, but .toString() method shows the local time.
Big note, UTC stands for Universal time code. The current time right now in 2 different places is the same UTC, but the output can be formatted differently.
What we need here is some formatting
var _date = new Date(1270544790922);
// outputs > "Tue Apr 06 2010 02:06:30 GMT-0700 (PDT)", for me
_date.toLocaleString('fi-FI', { timeZone: 'Europe/Helsinki' });
// outputs > "6.4.2010 klo 12.06.30"
_date.toLocaleString('en-US', { timeZone: 'Europe/Helsinki' });
// outputs > "4/6/2010, 12:06:30 PM"
This works but.... you can't really use any of the other date methods for your purposes since they describe the user's timezone. What you want is a date object that's related to the Helsinki timezone. Your options at this point are to use some 3rd party library (I recommend this), or hack-up the date object so you can use most of it's methods.
Option 1 - a 3rd party like moment-timezone
moment(1270544790922).tz('Europe/Helsinki').format('YYYY-MM-DD HH:mm:ss')
// outputs > 2010-04-06 12:06:30
moment(1270544790922).tz('Europe/Helsinki').hour()
// outputs > 12
This looks a lot more elegant than what we're about to do next.
Option 2 - Hack up the date object
var currentHelsinkiHoursOffset = 2; // sometimes it is 3
var date = new Date(1270544790922);
var helsenkiOffset = currentHelsinkiHoursOffset*60*60000;
var userOffset = _date.getTimezoneOffset()*60000; // [min*60000 = ms]
var helsenkiTime = new Date(date.getTime()+ helsenkiOffset + userOffset);
// Outputs > Tue Apr 06 2010 12:06:30 GMT-0700 (PDT)
It still thinks it's GMT-0700 (PDT), but if you don't stare too hard you may be able to mistake that for a date object that's useful for your purposes.
I conveniently skipped a part. You need to be able to define currentHelsinkiOffset. If you can use date.getTimezoneOffset() on the server side, or just use some if statements to describe when the time zone changes will occur, that should solve your problem.
Conclusion - I think especially for this purpose you should use a date library like moment-timezone.
To account for milliseconds and the user's time zone, use the following:
var _userOffset = _date.getTimezoneOffset()*60*1000; // user's offset time
var _centralOffset = 6*60*60*1000; // 6 for central time - use whatever you need
_date = new Date(_date.getTime() - _userOffset + _centralOffset); // redefine variable
Just another approach
function parseTimestamp(timestampStr) {
return new Date(new Date(timestampStr).getTime() + (new Date(timestampStr).getTimezoneOffset() * 60 * 1000));
};
//Sun Jan 01 2017 12:00:00
var timestamp = 1483272000000;
date = parseTimestamp(timestamp);
document.write(date);
Cheers!
I have a suspicion, that the Answer doesn't give the correct result. In the question the asker wants to convert timestamp from server to current time in Hellsinki disregarding current time zone of the user.
It's the fact that the user's timezone can be what ever so we cannot trust to it.
If eg. timestamp is 1270544790922 and we have a function:
var _date = new Date();
_date.setTime(1270544790922);
var _helsenkiOffset = 2*60*60;//maybe 3
var _userOffset = _date.getTimezoneOffset()*60*60;
var _helsenkiTime = new Date(_date.getTime()+_helsenkiOffset+_userOffset);
When a New Yorker visits the page, alert(_helsenkiTime) prints:
Tue Apr 06 2010 05:21:02 GMT-0400 (EDT)
And when a Finlander visits the page, alert(_helsenkiTime) prints:
Tue Apr 06 2010 11:55:50 GMT+0300 (EEST)
So the function is correct only if the page visitor has the target timezone (Europe/Helsinki) in his computer, but fails in nearly every other part of the world. And because the server timestamp is usually UNIX timestamp, which is by definition in UTC, the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT), we cannot determine DST or non-DST from timestamp.
So the solution is to DISREGARD the current time zone of the user and implement some way to calculate UTC offset whether the date is in DST or not. Javascript has not native method to determine DST transition history of other timezone than the current timezone of user. We can achieve this most simply using server side script, because we have easy access to server's timezone database with the whole transition history of all timezones.
But if you have no access to the server's (or any other server's) timezone database AND the timestamp is in UTC, you can get the similar functionality by hard coding the DST rules in Javascript.
To cover dates in years 1998 - 2099 in Europe/Helsinki you can use the following function (jsfiddled):
function timestampToHellsinki(server_timestamp) {
function pad(num) {
num = num.toString();
if (num.length == 1) return "0" + num;
return num;
}
var _date = new Date();
_date.setTime(server_timestamp);
var _year = _date.getUTCFullYear();
// Return false, if DST rules have been different than nowadays:
if (_year<=1998 && _year>2099) return false;
// Calculate DST start day, it is the last sunday of March
var start_day = (31 - ((((5 * _year) / 4) + 4) % 7));
var SUMMER_start = new Date(Date.UTC(_year, 2, start_day, 1, 0, 0));
// Calculate DST end day, it is the last sunday of October
var end_day = (31 - ((((5 * _year) / 4) + 1) % 7))
var SUMMER_end = new Date(Date.UTC(_year, 9, end_day, 1, 0, 0));
// Check if the time is between SUMMER_start and SUMMER_end
// If the time is in summer, the offset is 2 hours
// else offset is 3 hours
var hellsinkiOffset = 2 * 60 * 60 * 1000;
if (_date > SUMMER_start && _date < SUMMER_end) hellsinkiOffset =
3 * 60 * 60 * 1000;
// Add server timestamp to midnight January 1, 1970
// Add Hellsinki offset to that
_date.setTime(server_timestamp + hellsinkiOffset);
var hellsinkiTime = pad(_date.getUTCDate()) + "." +
pad(_date.getUTCMonth()) + "." + _date.getUTCFullYear() +
" " + pad(_date.getUTCHours()) + ":" +
pad(_date.getUTCMinutes()) + ":" + pad(_date.getUTCSeconds());
return hellsinkiTime;
}
Examples of usage:
var server_timestamp = 1270544790922;
document.getElementById("time").innerHTML = "The timestamp " +
server_timestamp + " is in Hellsinki " +
timestampToHellsinki(server_timestamp);
server_timestamp = 1349841923 * 1000;
document.getElementById("time").innerHTML += "<br><br>The timestamp " +
server_timestamp + " is in Hellsinki " + timestampToHellsinki(server_timestamp);
var now = new Date();
server_timestamp = now.getTime();
document.getElementById("time").innerHTML += "<br><br>The timestamp is now " +
server_timestamp + " and the current local time in Hellsinki is " +
timestampToHellsinki(server_timestamp);​
And this print the following regardless of user timezone:
The timestamp 1270544790922 is in Hellsinki 06.03.2010 12:06:30
The timestamp 1349841923000 is in Hellsinki 10.09.2012 07:05:23
The timestamp is now 1349853751034 and the current local time in Hellsinki is 10.09.2012 10:22:31
Of course if you can return timestamp in a form that the offset (DST or non-DST one) is already added to timestamp on server, you don't have to calculate it clientside and you can simplify the function a lot. BUT remember to NOT use timezoneOffset(), because then you have to deal with user timezone and this is not the wanted behaviour.
Presuming you get the timestamp in Helsinki time, I would create a date object set to midnight January 1 1970 UTC (for disregarding the local timezone settings of the browser).
Then just add the needed number of milliseconds to it.
var _date = new Date( Date.UTC(1970, 0, 1, 0, 0, 0, 0) );
_date.setUTCMilliseconds(1270544790922);
alert(_date); //date shown shifted corresponding to local time settings
alert(_date.getUTCFullYear()); //the UTC year value
alert(_date.getUTCMonth()); //the UTC month value
alert(_date.getUTCDate()); //the UTC day of month value
alert(_date.getUTCHours()); //the UTC hour value
alert(_date.getUTCMinutes()); //the UTC minutes value
Watch out later, to always ask UTC values from the date object. This way users will see the same date values regardless of local settings.
Otherwise date values will be shifted corresponding to local time settings.
My solutions is to determine timezone adjustment the browser applies, and reverse it:
var timestamp = 1600913205; //retrieved from unix, that is why it is in seconds
//uncomment below line if you want to apply Pacific timezone
//timestamp += -25200;
//determine the timezone offset the browser applies to Date()
var offset = (new Date()).getTimezoneOffset() * 60;
//re-initialize the Date function to reverse the timezone adjustment
var date = new Date((timestamp + offset) * 1000);
//here continue using date functions.
This point the date will be timezone free and always UTC, You can apply your own offset to timestamp to produce any timezone.
Use this and always use UTC functions afterwards e.g. mydate.getUTCHours();
function getDateUTC(str) {
function getUTCDate(myDateStr){
if(myDateStr.length <= 10){
//const date = new Date(myDateStr); //is already assuming UTC, smart - but for browser compatibility we will add time string none the less
const date = new Date(myDateStr.trim() + 'T00:00:00Z');
return date;
}else{
throw "only date strings, not date time";
}
}
function getUTCDatetime(myDateStr){
if(myDateStr.length <= 10){
throw "only date TIME strings, not date only";
}else{
return new Date(myDateStr.trim() +'Z'); //this assumes no time zone is part of the date string. Z indicates UTC time zone
}
}
let rv = '';
if(str && str.length){
if(str.length <= 10){
rv = getUTCDate(str);
}else if(str.length > 10){
rv = getUTCDatetime(str);
}
}else{
rv = '';
}
return rv;
}
console.info(getDateUTC('2020-02-02').toUTCString());
var mydateee2 = getDateUTC('2020-02-02 02:02:02');
console.info(mydateee2.toUTCString());
// you are free to use all UTC functions on date e.g.
console.info(mydateee2.getUTCHours())
console.info('all is good now if you use UTC functions')

Categories

Resources