So i have a json object, which returned me basically a datetime object, now the question, what is the most efficient way of formatting this to a single string human readable format, in the users (client) local timezone... In javascript
created: {
timezone: {
name: "America/New_York",
location: {
country_code: "US",
latitude: 40.71417,
longitude: -74.00639,
comments: "Eastern Time"
}
},
offset: -18000,
timestamp: 1454125056
},
If the timestamp is an ECMAScript time value (i.e. milliseconds since 1970-01-01T00:00:00Z) then you can give that value directly to a Date object:
var d = new Date(1454125056); // 1970-01-17T19:55:25.056Z
however it is more likely seconds, so multiply by 1,000:
new Date(1454125056*1000).toISOString(); // 2016-01-30T03:37:36.000Z
which will create a Date for that moment in time. The offset should probably be ignored, unless it was used in the creation of the time value, in which case it should be added if it follows the ISO convention of negative for west and positive for east. If it follows the ECMAScript convention, the opposite applies.
I'll assume ISO, and since it appears to be seconds, you can apply it to the UTC seconds:
var offset = -18000;
d.setUTCSeconds(d.getUTCSeconds() + offset);
console.log(d.toISOString()); // 2016-01-29T22:37:36.000Z
Using plain Date methods thereafter will return values based on the host system's timezone settings.
var timeValue = 1454125056;
var offset = -18000;
var d = new Date(timeValue*1000);
document.write(d.toISOString() + '<br>' + d);
d.setUTCSeconds(d.getUTCSeconds() + offset);
document.write('<br>' + d.toISOString() + '<br>' + d);
There are many questions here on how to format a date string from a Date object.
Note that javascript is only required consider the daylight saving rules in force at the current time as if they had always existed, so be careful with historical dates.
Suppose this json object loaded in $created variable. i assume you mean php.
in PHP :
$obj = json_decode($created, true);
$timezone_name = $obj['timezone']['name'];
$timezone_location_country_code = $obj['timezone']['location']['country_code'];
$timezone_location_latitude = $obj['timezone']['location']['latitude'];
$timezone_location_longitude = $obj['timezone']['location']['longitude'];
$timezone_location_comments = $obj['timezone']['location']['comments'];
$offset = $obj['offset'];
$timestamp = date('m/d/Y', abs($obj['timestamp']));
in Javascript :
getDate: function(timestamp){
// Multiply by 1000 because JS works in milliseconds instead of the UNIX seconds
var date = new Date(timestamp * 1000);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1; // getMonth() is zero-indexed, so we’ll increment to get the correct month number
var day = date.getUTCDate();
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var seconds = date.getUTCSeconds();
month = (month < 10) ? ‘0’ + month : month;
day = (day < 10) ? ‘0’ + day : day;
hours = (hours < 10) ? ‘0’ + hours : hours;
minutes = (minutes < 10) ? ‘0’ + minutes : minutes;
seconds = (seconds < 10) ? ‘0’ + seconds: seconds;
return year + ‘-‘ + month + ‘-‘ + day + ‘ ‘ + hours + ‘:’ + minutes;
}
Related
I want to add 30 days to a Date (including the timestamp), however, the timestamp is being calculated from the execution time of the script instead of the source data (loadStartDateTime).
I created a new date object and then set the date (purge_date = loadStartDateTime + 30days).
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
PURGEDATE = (function (loadTime) {
var loadDate = new Date(loadTime);
var purge_date = new Date();
purge_date.setDate(loadDate.getDate()+30);
var month = purge_date.getMonth() + 1;
var mm = month < 10 ? "0" + month : month;
var day = purge_date.getDate();
var dd = day < 10 ? "0" + day : day;
var hours = purge_date.getHours() < 10 ? "0" + purge_date.getHours() : purge_date.getHours();
var minutes = purge_date.getMinutes() < 10 ? "0" + purge_date.getMinutes() : purge_date.getMinutes();
var seconds = purge_date.getSeconds() < 10 ? "0" + purge_date.getSeconds() : purge_date.getSeconds();
var time = hours + ":" + minutes + ":" + seconds;
var yyyy = purge_date.getFullYear();
return mm + "/" + dd + "/" + yyyy + time;
})(LoadStartDateTime)
The Result:
loadStartDateTime | PurgeDate
8/7/2018 5:55:45 PM | 09/06/2018 10:28:49
8/7/2018 5:58:10 PM | 09/06/2018 10:28:49
I saw an example doing some math with the dates, should I make the calculations of the timestamp separately?
Thank you~
After further investigation I realized that:
The Date object’s constructor is ISO 8601
When I use getDate() I do not provide the timezone explicitly.
This causes the timestamp to be 00:00:00 local time, so I should use getTime() method instead to get the timestamp. Since in JavaScript a timestamp is the number of milliseconds, a simple way to get it done is to send the timestamp value in the Date constructor. To calculate 30 days measured in timestamp:
30 * 24 * 60 * 60 * 1000
Finally, sum both values and send the result as a param in the constructor:
For example:
loadStartDateTime = new Date('8/7/2018 5:55:45 PM');
test_date = loadStartDateTime.getTime() + (30 * 24 * 60 * 60 * 1000);
test_date = new Date(test_date);
and then can continue with the Date Formatting.
I found the solution combining the answers from ISO 8601 date format - Add day with javascript and Add 30 days to date (mm/dd/yy). This guide "The Definitive Guide to DateTime Manipulation" helped to find out when I was wrong by understanding more about DateTime Manipulation.
What's the best way to convert date time formats using javascript?
I have this.. "2015-08-06T00:39:08Z"
and would like to change it to
"06/08/2015 12:39pm"
You could do it manually by instantiating a Date object:
var d = new Date('2015-08-06T00:39:08Z');
Then using the Date methods (like getDay or getUTCFullYear) to get the information needed and build the formatted string.
Or, if you don't mind relying on a library, you could use http://momentjs.com/ that provides a lot of methods, and particularly the format method: http://momentjs.com/docs/#/displaying/format/
// Example with moment.js
var formattedDate = moment('2015-08-06T00:39:08Z').format("MM/DD/YYYY hh:mma");
alert(formattedDate);
Use newDate() method, then Date Get Methods. Examples are explained on w3Schools
Method Description
getDate() Get the day as a number (1-31)
getDay() Get the weekday as a number (0-6)
getFullYear() Get the four digit year (yyyy)
getHours() Get the hour (0-23)
getMilliseconds() Get the milliseconds (0-999)
getMinutes() Get the minutes (0-59)
getMonth() Get the month (0-11)
getSeconds() Get the seconds (0-59)
getTime() Get the time (milliseconds since January 1, 1970)
With pure javascript:
code:
function formatDate(input) {
var datePart = input.match(/\d+/g),
year = datePart[0], // get only two digits
month = datePart[1],
day = datePart[2];
var h = parseInt(input.substr(input.indexOf("T") + 1, 2));
var m = parseInt(input.substr(input.indexOf(":") + 1, 2));
var dd = "AM";
if (h >= 12) {
h = hh - 12;
dd = "PM";
}
if (h == 0) {
h = 12;
}
m = m < 10 ? "0" + m : m;
alert(day + '/' + month + '/' + year + ' ' + h.toString() + ':' + m.toString() + dd);
}
formatDate('2015-08-06T00:39:08Z'); // "18/01/10"
I am using the HTML5 element datetime-local. I need to have two formats of the date. One as a date object the other as a string. I am going to store the date object in the database and I am going to use the string to set the datetime-local form input.
I need to convert this string to a date object:
"2014-06-22T16:01"
I can't seem to get the correct time. This is what I am getting. The time not correct.
Sun Jun 22 2014 09:01:00 GMT-0700 (PDT)
This is the how I am formating the date:
function formatTime(_date) {
var _this = this,
date = (_date) ? _date : new Date(),
day = date.getDate(),
month = date.getMonth() + 1,
year = date.getFullYear(),
hour = date.getHours(),
minute = date.getMinutes(),
seconds = date.getSeconds(),
function addZero(num) {
return num > 9 ? num : '0' + num;
}
minute = addZero(minute);
seconds = addZero(seconds);
hour = addZero(hour);
day = addZero(day);
month = addZero(month);
return year + '-' + month + '-' + day + 'T' + hour + ':' + minute;
};
Example:
http://codepen.io/zerostyle/pen/gwpuK/
If you are trying to get an ISO 8601 date string, you can try Date.prototype.toISOString. However, it always uses UTC. If you want to include the local timezone, use something like the following:
/* Return a string in ISO 8601 format with current timezone offset
** e.g. 2014-10-02T23:31:03+0800
** d is a Date object, or defaults to current Date if not supplied.
*/
function toLocalISOString(d) {
// Default to now if no date provided
d = d || new Date();
// Pad to two digits with leading zeros
function pad(n){
return (n<10?'0':'') + n;
}
// Pad to three digits with leading zeros
function padd(n){
return (n<100? '0' : '') + pad(n);
}
// Convert offset in mintues to +/-HHMM
// Note change of sign
// e.g. -600 => +1000, +330 => -0530
function minsToHHMM(n){
var sign = n<0? '-' : '+';
n = Math.abs(n);
var hh = pad(n/60 |0);
var mm = pad(n%60);
return sign + hh + mm;
}
var offset = minsToHHMM(d.getTimezoneOffset() * -1);
return d.getFullYear() + '-' + pad(d.getMonth() + 1) + '-' + pad(d.getDate()) +
'T' + pad(d.getHours()) + ':' + pad(d.getMinutes()) + ':' + pad(d.getSeconds()) +
'.' + padd(d.getMilliseconds()) + offset;
}
console.log(toLocalISOString(new Date())); // 2014-06-23T07:58:04.773+0800
Edit
The above probably misses your question, which seems to be;
I need to convert this string to a date object: "2014-06-22T16:01"
Presumaly you want to treat it as a local time string. ECMA-262 says that ISO–like strings without a timezone are to be treated as UTC, and that is what your host seems to be doing. So you need a function to create a local Date object from the string:
function parseYMDHM(s) {
var b = s.split(/\D+/);
return new Date(b[0], --b[1], b[2], b[3], b[4], b[5]||0, b[6]||0);
}
console.log(parseYMDHM('2014-06-22T16:01')); // Sun Jun 22 16:01:00 UTC+0800 2014
A third party is providing me with an EDT time-stamp in the following format:
MM/DD/YYYY hh:mm
for instance: '08/19/2013 11:31'
I need to convert it to PST with JavaScript (same date time format) and have been looking all over but can't find any info about doing this.. If someone can help me with some example code I would really appreciate it.
If you wanted to do this manually, you can try the following:
Split by a space, so you have date and time.
Split the time by ":" and split the date by "/".
Create a new Date() and provide the right values in the right order.
Subtract 3 hours using the proper methods, then recreate the format.
Here's an example of all this:
var est = "01/01/2014 02:31",
finalDate, pst;
finalDate = parseDateString(est);
finalDate.setHours(finalDate.getHours() - 3);
pst = formatDate(finalDate);
console.log(pst);
function parseDateString(str) {
var dateTime, date, time, dateSplit, month, day, year, timeSplit, hour, minute;
dateTime = est.split(" ");
date = dateTime[0];
time = dateTime[1];
dateSplit = date.split("/");
month = dateSplit[0] - 1;
day = dateSplit[1];
year = dateSplit[2];
timeSplit = time.split(":");
hour = timeSplit[0];
minute = timeSplit[1];
return new Date(year, month, day, hour, minute);
}
function formatDate(d) {
return padZero(d.getMonth() + 1) + "/" + padZero(d.getDate()) + "/" + d.getFullYear() + " " + padZero(d.getHours()) + ":" + padZero(d.getMinutes());
}
function padZero(num) {
if (+num < 10) {
num = "0" + num;
}
return "" + num;
}
DEMO: http://jsfiddle.net/MmVmR/
The padZero function is there just to prepend any 0s in case the number is less than 10.
Reference:
Dates in JS - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Determining a user's timezone server side and converting from UTC has proven more trouble than its worth.
Is there a reliable way for javascript/jquery to determine the timezone of the user and apply the offset to a UTC datetime stamp (2012-08-25 10:59:56.511479) and output in my desired format (Aug 25 '12 - 10:59AM)?
What might the jquery code look like to say
// dom ready
$('span.localtime').each(function(e) {
// get stamp and apply conversion
});
.getTimezoneOffset() is available on the date object, and gives you the offset from UTC in minutes.
var offset = (new Date()).getTimezoneOffset();
// convert myUtcDate to a date in local time
myUtcDate.setMinutes(myUtcDate.getMinutes() + (offset*-1));
Thus:
$('.span.localtime').each(function() {
var myUtcDate = new Date($(this).html()); // assuming "2012-08-25 10:59:56.511479"
myUtcDate.setMinutes(myUtcDate.getMinutes() + (myUtcDate.getTimezoneOffset() * -1));
$(this).html(myUtcDate.toString());
});
Note that myUtcDate.toString() could be replaced with any date formatting you want. In your case, it might look like
$(this).html(formatDate(myUtcDate));
function formatDate(d) {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var y = d.getFullYear().toString().slice(-2); // "12"
var m = months[d.getMonth()]; // "Aug"
var d = d.getDate(); // "25"
var ampm = 'AM';
var h = d.getHours();
if(h>=12) {
h -= 12;
ampm = 'PM';
}
if(h == 0)
h = 12;
var min = ("00" + d.getMinutes()).slice(-2);
return m + " " + d + " '" + y + " - " + h + ":" + min + ampm;
}
You might want to use a date format plugin for formatting dates in a neater more reliable manner.
Also, have a look at https://github.com/GregDThomas/jquery-localtime - it wraps all this up in a simple to use jQuery plugin.