I have a mySQL database in which I store the time in this format automatically:
2015-08-17 21:31:06
I am able to retrieve this time stamp from my database and bring it into javascript. I want to then get the current date time in javascript and determine how many days are between the current date time and the date time I pulled from the database.
I found this function when researching how to get the current date time in javascript:
Date();
But it seems to return the date in this format:
Tue Aug 18 2015 10:49:06 GMT-0700 (Pacific Daylight Time)
There has to be an easier way of doing this other than going character by character and picking it out from both?
You can build a new date in javascript by passing the data you receive from your backend as the first argument.
You have to make sure that the format is an accepted one. In your case we need to replace the space with a T. You may also be able to change the format from the back end.
Some good examples are available in the MDN docs.
var d = new Date("2015-08-17T21:31:06");
console.log(d.getMonth());
To calculate the difference in days you could do something like this:
var now = new Date();
var then = new Date("2015-08-15T21:31:06");
console.log((now - then)/1000/60/60/24);
You can select the difference directly in your query:
SELECT DATEDIFF(now(), myDateCol) FROM myTable;
the Date object has a function called getTime(), which will give you the current timestamp in milliseconds. You can then get the diff and convert to days by dividing by (1000 * 3600 * 24)
e.g.
var date1 = new Date()
var date2 = new Date()
var diffInMs = date2.getTime() - date1.getTime()
var diffInDays = diffInMs/(1000*3600*24)
Since none of the other answer got it quite right:
var pieces = "2015-08-17 21:31:06".split(' ');
var date = pieces[0].split('-');
var time = pieces[1].split(':');
var yr = date[0], mon = date[1], day = date[2];
var hour = time[0], min = time[1], sec = time[2];
var dateObj = new Date(yr, mon, day, hr, min, sec);
//if you want the fractional part, omit the call to Math.floor()
var diff = Math.floor((Date.now() - dateObj.getTime()) / (1000 * 60 * 60 * 24));
Note that none of this deals with the timezone difference between the browser and whatever you have stored in the DB. Here's an offset example:
var tzOff = new Date().getTimezoneOffset() * 60 * 1000; //in ms
Related
I'm a newbie and recently started to read Beginning Javascript, by McPeak and Wilton. The authors propose an exercise about dates calculation. This is the exercise
Using the Date type, calculate the date 12 months from now.
I tried to solve it with this code
//gets today's date
var today = new Date();
//this line transforms the date in milliseconds
var daysAsMilliseconds = 1000* 60 * 60 * 24 * today.getDate();
//creates a new Date object
console.log(new Date(today.setDate(365) + daysAsMilliseconds));
The result I get here is correct(August 11th 2018).
Later, I wonder if it was really necessary to create 2 variables and tried this solution:
var today = new Date();
console.log(new Date(today.setDate(365) + (1000 * 60 * 60 * 24 * today.getDate())));
Here the solution was incorrect. The console showed August 31 2018. Why?
If necessary, here you will find the repl.it with the code
You call setDate, before you call getDate , therefore getDate will always return 365. Simply swapp it:
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365))
Or its may easier to work with months directly:
today.setMonth(today.getMonth() + 12);
var intwelvemonths = today;
All you need to do is add 1 to the year:
var yearFromNow = new Date();
yearFromNow.setYear(yearFromNow.getFullYear() + 1);
Setting the date to 365 makes no sense; .setDate() is for day-of-month, so setting it to that constant moves the date a year (usually) from the last day of the previous month. And you don't need to do any other math outside of the date API; just increment the year, and you're done.
You're calling today.setDate(365) before you're adding the results of today.getDate(): today.getDate() will give the date that you set, not today's date.
Changing the order of operations will do the trick:
var today = new Date();
new Date((1000 * 60 * 60 * 24 * today.getDate()) + today.setDate(365));
I recommend you to use a package as moment.js because it manage a lot of date formats, and it has very good implementations for date managing.
Using moment js for add.
moment().add(Number, String);
Example
var m = moment(new Date(2011, 2, 12, 5, 0, 0));
m.hours(); // 5
m.add(1, 'days').hours(); // 5
For more docs see moment().add() docs
I have a challenge where backend data is always stored in UTC time. Our front-end data is always presented in CST. I don't have access to this 'black box.'
I would like to mirror this in our data warehouse. Which is based in Europe (CET). So "local" conversion will not work.
I'm wondering the simplest, most straightforward way to accurately convert UTC time (I can have it in epoch milliseconds or a date format '2015-01-01 00:00:00') to Central Standard Time. (which is 5 or 6 hours behind based on Daylight Savings).
I see a lot of threads about converting to 'local' time ... again I don't want this, nor do I simply want to subtract 6 hours which will be wrong half the year.
Anyone have any ideas? This seems to be a very common problem but I've been searching for a while, and have found nothing.
Using moment.js with the moment-timezone add-on makes this task simple.
// construct a moment object with UTC-based input
var m = moment.utc('2015-01-01 00:00:00');
// convert using the TZDB identifier for US Central time
m.tz('America/Chicago');
// format output however you desire
var s = m.format("YYYY-MM-DD HH:mm:ss");
Additionally, since you are referring to the entire North American Central time zone, you should say either "Central Time", or "CT". The abbreviation "CST" as applied to North America explicitly means UTC-6, while the "CDT" abbreviation would be used for UTC-5 during daylight saving time.
Do be careful with abbreviations though. "CST" might mean "China Standard Time". (It actually has five different interpretations).
You can use the time zone offset to determine whether 5 or 6 hours should be subtracted.
var dateJan;
var dateJul;
var timezoneOffset;
var divUTC;
var divCST;
// Set initial date value
dateValue = new Date('10/31/2015 7:29:54 PM');
divUTC = document.getElementById('UTC_Time');
divCST = document.getElementById('CST_Time');
divUTC.innerHTML = 'from UTC = ' + dateValue.toString();
// Get dates for January and July
dateJan = new Date(dateValue.getFullYear(), 0, 1);
dateJul = new Date(dateValue.getFullYear(), 6, 1);
// Get timezone offset
timezoneOffset = Math.max(dateJan.getTimezoneOffset(), dateJul.getTimezoneOffset());
// Check if daylight savings
if (dateValue.getTimezoneOffset() < timezoneOffset) {
// Adjust date by 5 hours
dateValue = new Date(dateValue.getTime() - ((1 * 60 * 60 * 1000) * 5));
}
else {
// Adjust date by 6 hours
dateValue = new Date(dateValue.getTime() - ((1 * 60 * 60 * 1000) * 6));
}
divCST.innerHTML = 'to CST = ' + dateValue.toString();
<div id="UTC_Time"></div>
<br/>
<div id="CST_Time"></div>
Maybe you can use something like the following. Note, that is just an example you might need to adjust it to your needs.
let cstTime = new Date(createdAt).toLocaleString("es-MX", {
timeZone: "America/Mexico_City" });
You can use below code snippet for converting.
function convertUTCtoCDT() {
var timelagging = 6; // 5 or 6
var utc = new Date();
var cdt = new Date(utc.getTime()-((1 * 60 * 60 * 1000) * timelagging));
console.log("CDT: "+cdt);
}
let newDate = moment(new Date()).utc().format("YYYY-MM-DD HH:mm:ss").toString()
var m = moment.utc(newDate);
m.tz('America/Chicago');
var cstDate = m.format("YYYY-MM-DD HH:mm:ss");
You can use below code snippet
// Get time zone offset for CDT or CST
const getCdtCstOffset = () => {
const getNthSunday = (date, nth) => {
date.setDate((7*(nth-1))+(8-date.getDay()));
return date;
}
const isCdtTimezoneOffset = (today) => {
console.log('Today : ', today);
let dt = new Date();
var mar = new Date(dt.getFullYear(), 2, 1);
mar = getNthSunday(mar, 2);
console.log('CDT Start : ', mar);
var nov = new Date(dt.getFullYear(), 10, 1, 23, 59, 59);
nov = getNthSunday(nov, 1);
console.log('CDT End : ', nov);
return mar.getTime()< today.getTime() && nov.getTime()> today.getTime();
}
var today = new Date()// current date
if (isCdtTimezoneOffset(today)) {
return -5
} else {
return -6
}
}
let cstOrCdt = new Date();
cstOrCdt.setHours(cstOrCdt.getHours()+getCdtCstOffset())
console.log('CstOrCdt : ', cstOrCdt);
I am using JavaScript and JQuery. I am trying to calculate time difference between current time on my machine and a given time in below format.
December 12 2015 14:00:00 UTC-0800
The above format contains TimeZone and the problem is, it can be any timezone in the above time format.
is there any predefined function to calculate the time difference easily ?
If moment.js is an option, you can use that to parse the time string, and retrieve a timezone-corrected Date object. You can them compare that to the local time:
var datestr = "December 12 2015 14:00:00 UTC-0800";
// get target time as a JavaScript Date
var m = moment(datestr, "MMMM DD YYYY HH:mm:ss [UTC]Z").toDate();
var now = new Date(); // current time as a Date
// get the difference (in milliseconds) between the two
var diffInMs = m - now;
// use moment.duration to display it in a readable form
var dur = moment.duration(diffInMs, "ms");
console.log( dur.humanize() );
var hours = Math.floor( diffInMs / (1000 * 60 * 60) );
var seconds = Math.floor( diffInMs / 1000 );
console.log( "hours: " + hours );
console.log( "seconds: " + seconds );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
The date is stored in the database as datetimeoffset(7).
The MVC controller gets the date from the database in the format "10/8/2015 6:05:12 PM -07:00" and passes it to the view as it is. I am trying to convert it to the correct date to show that in the view as mm/dd/yyy by doing the following:
var myDate = "10/8/2015 6:05:12 PM -07:00";
var newDate = New Date(myDate);
Then I'm formatting it to mm/dd/yyyy format after extracting the day, month and year.
IE11 and Safari do not like this and show error "Invalid date" in the console at the line
var newDate = New Date(myDate)
Chrome or Firefox doesn't show any problems.
Now I know that "10/8/2015 6:05:12 PM -07:00" is not a valid datestring. So my question is, how to handle this situation so all major browsers will show the correct date?
This function should work, I'm aware it needs some refactoring but it may be a good starting point.
function readDate(inputDate) {
// extract the date that can be parsed by IE ("10/8/2015 6:05:12 PM")
// and the timezone offset "-07:00"
var parsedDate = /([\s\S]*?)\s*([+-][0-9\:]+)$/.exec(inputDate);
//create new date with "datetimeoffset" string
var dt = new Date(parsedDate[1]);
// get millisecs
var localTime = dt.getTime();
// get the offset in millisecs
// notice the conversion to milliseconds
// the variable "localTzOffset" can be negative
// because the standar (http://www.w3.org/TR/NOTE-datetime)
var localTzOffset = dt.getTimezoneOffset() * 60 * 1000;
// to get UTC time
var utcTime = localTime + localTzOffset;
// extract hours and minutes difference
// for given timezone
var parsed = /([+-][0-9]+)\:([0-9]+)/.exec(parsedDate[2]);
var hours = parseInt(parsed[1]);
var minutes = parseInt(parsed[2]);
// convert extracted difference to milliseconds
var tzOffset = Math.abs(hours * 60 * 60 * 1000) + (minutes * 60 * 1000);
// taking into accout if negative
tzOffset = hours > 1 ? tzOffset : tzOffset * -1;
// construct the result Date
return new Date(utcTime + tzOffset);
}
Usage:
var date = readDate("10/8/2015 6:05:12 PM -07:00");
It seems that JavaScript's Date() function can only return local date and time. Is there anyway to get time for a specific time zone, e.g., GMT-9?
Combining #Esailija and #D3mon-1stVFW, I figured it out: you need to have two time zone offset, one for local time and one for destination time, here is the working code:
var today = new Date();
var localoffset = -(today.getTimezoneOffset()/60);
var destoffset = -4;
var offset = destoffset-localoffset;
var d = new Date( new Date().getTime() + offset * 3600 * 1000)
An example is here: http://jsfiddle.net/BBzyN/3/
var offset = -8;
new Date( new Date().getTime() + offset * 3600 * 1000).toUTCString().replace( / GMT$/, "" )
"Wed, 20 Jun 2012 08:55:20"
<script>
var offset = -8;
document.write(
new Date(
new Date().getTime() + offset * 3600 * 1000
).toUTCString().replace( / GMT$/, "" )
);
</script>
You can do this in one line:
let d = new Date(new Date().toLocaleString("en-US", {timeZone: "timezone id"})); // timezone ex: Asia/Jerusalem
var today = new Date();
var offset = -(today.getTimezoneOffset()/60);
You can always get GMT time (so long as the client's clock is correct).
To display a date in an arbitrary time-zone, construct a string from the UTC hours, minutes, and seconds after adding the offset.
There is simple library for working on timezones easily called TimezoneJS can be found at https://github.com/mde/timezone-js.