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"
Related
My database value is this
2020-03-08 20:44:00
But in javascript. It display
Mon Mar 09 2020 09:44:00 GMT+0800 (Singapore Standard Time)
Want i want to display on UI
2020-03-08 20:44:00
or
2020-03-08
Is there a way to remove the timezone and get only the actual value from the database.
toISOString is not a proper way to get date into DateTime. please follow the below method to get a date from DateTime.
var date = new Date("2020-03-08 20:44:00");
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
var newDate = year + '-' + month + '-' + day;
console.log("Date plush time - "+date);
console.log("Only Date - "+newDate);
You're using the silently using Date object's .toString() method which converts the UTC date (that your database is storing) into a time in the current time zone.
If date is the variable that you get from your database, then you can format it like you want it like this:
let dateString = date.toISOString().replace('T', ' ').replace(/\..+/, '')
This will take your date, convert it into an ISO string (in the form 2020-01-10T03:09:24.551Z) and replace the T with a space and everything after the decimal with nothing.
Try this.
let d = new Date('2020-03-08 20:44:00');
console.log(`${d.getFullYear()}-${d.getMonth() < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1}-${d.getDate() < 10 ? '0' + (d.getDate()): d.getDate()}`);
You can take each part of the date and construct your own format
example:
let formatted_date = my_date.getFullYear() + "-" + (my_date.getMonth() + 1) + "-" + my_date.getDate()
in this example: my_date hold the date you want to display.
If you're able to use a library, use moment.js
https://momentjs.com/docs/#/displaying/
moment("2020-03-08 20:44:00").format("YYYY-MM-DD");
or
moment(new Date("2020-03-08 20:44:00")).format("YYYY-MM-DD");
It can even change the time to utc
https://momentjs.com/guides/#/parsing/local-utc-zone/
moment.utc("2020-03-08 20:44:00").format("YYYY-MM-DD");
hope this helps :)
Subtract your timezone offset milliseconds.
var dt = new Date('2020-03-08 20:44:00');
dt = new Date(dt.getTime()-dt.getTimezoneOffset()*60000);
console.log(dt.toUTCString());
var mo = dt.getUTCMonth()+1, d = dt.getUTCDate(), h = dt.getUTCHours();
var m = dt.getUTCMinutes(), s = dt.getUTCSeconds();
if(mo < 10)mo = '0'+mo;
if(d < 10)d = '0'+d;
if(h < 10)h = '0'+h;
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
console.log(dt.getUTCFullYear()+'-'+mo+'-'+d+' '+h+':'+m+':'+s);
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
i have an epoch time: x = 1383483902000
I am trying to get a date like: dd-mm-yyyy and want to do this without additional library.
I have tried several ways and my last method end up like :
var date = new Date(Math.round(Number(x)));
but i get an ugly thing like: sun nov 03 2013 14:05:02 GMT+01:00
Use your date object to extract/format the parts you want:
var formattedDate = date.getUTCDate() + '-' + (date.getUTCMonth() + 1)+ '-' + date.getUTCFullYear()
The example below uses the UTC methods of the date object as you are dealing with epoch time (which is milliseconds since epoch in UTC):
var formatDate = function formatDate(date) { // function for reusability
var d = date.getUTCDate().toString(), // getUTCDate() returns 1 - 31
m = (date.getUTCMonth() + 1).toString(), // getUTCMonth() returns 0 - 11
y = date.getUTCFullYear().toString(), // getUTCFullYear() returns a 4-digit year
formatted = '';
if (d.length === 1) { // pad to two digits if needed
d = '0' + d;
}
if (m.length === 1) { // pad to two digits if needed
m = '0' + m;
}
formatted = d + '-' + m + '-' + y; // concatenate for output
return formatted;
},
x = 1383483902000, // sample time in ms since epoch
d = new Date(x), // convert to date object
f = formatDate(d); // pass to formatDate function to get dd-mm-yyyy
console.log(f); // log output to console for testing
You can run this in the browser console as-is.
function formatDate(value: any): any{
let date = new Date(Math.round(Number(value)));
let day = ("0" + date.getDate()).slice(-2);
let month = ("0" + (date.getMonth() + 1)).slice(-2);
let formatDate = date.getFullYear()+"-"+(month)+"-"+(day) ;
return formatDate;
}
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.