How to get correct gmt time in Javascript - javascript

For using the Amazon mechanical turk API I want to get the current GMT time and show it in ISO format
2011-02-24T20:38:34Z
I am wondering if there is any way to correctly get the gmt time and also be able to reformat it with ISO format. I can use something like now.toGMTString(); but it makes a string out of the date and it is hard to reformat it with ISO.

var year = now.getUTCFullYear()
var month = now.getUTCMonth()
var day= now.getUTCDay()
var hour= now.getUTCHours()
var mins= now.getUTCMinutes()
var secs= now.getUTCSeconds()
var dateString = year + "-" + month + "-" + day + "T" + hour + ":" + mins + ":" + secs + "Z"
You should be using UTC now instead of GMT. (Amounts to almost the same thing now, and it is the new standard anyway)

I believe this will work for you:
Number.prototype.pad = function(width,chr){
chr = chr || '0';
var result = this;
for (var a = 0; a < width; a++)
result = chr + result;
return result.slice(-width);
}
Date.prototype.toISOString = function(){
return this.getUTCFullYear().pad(4) + '-'
+ this.getUTCMonth().pad(2) + '-'
+ this.getUTCDay().pad(2) + 'T'
+ this.getUTCHours().pad(2) + ':'
+ this.getUTCMinutes().pad(2) + ':'
+ this.getUTCSeconds().pad(2) + 'Z';
}
Usage:
var d = new Date;
alert('ISO Format: '+d.toISOString());
Not much more different than every else's answer, but make it built-in to the date object for convenience

function pad(num) {
return ("0" + num).slice(-2);
}
function formatDate(d) {
return [d.getUTCFullYear(),
pad(d.getUTCMonth() + 1),
pad(d.getUTCDate())].join("-") + "T" +
[pad(d.getUTCHours()),
pad(d.getUTCMinutes()),
pad(d.getUTCSeconds())].join(":") + "Z";
}
formatDate(new Date());
Output:
"2011-02-24T21:01:55Z"

This script can take care of it
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'}
var d = new Date();
document.write(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

Related

Convert Round-Trip Time Pattern in ES6

I'm trying to convert something like this 2020-10-01T17:00:00.000Z to the correct time something like 06:00:00 PM. Pls see my code below:
const date = "2020-10-01T17:00:00.000Z";
const output = new Date(date).toLocaleTimeString('en-US');
console.log(output);
If you specifically need the time to be in UTC (instead of the local user's timezone), then I think you would need to build your own formatter function to do it, e.g.:
function formatDate(str, includeDate){
const date = new Date(str);
const hours = date.getUTCHours();
let twoDigits = (no) => {
const str = no.toString();
return (str.length === 1 ? '0' + str : str);
};
let strdate = (includeDate ? twoDigits(date.getUTCMonth() + 1) + '/' + twoDigits(date.getUTCDate()) + '/' + twoDigits(date.getUTCFullYear()) + ' ' : '');
if(12 <= hours) {
return strdate + twoDigits(hours === 12 ? 12 : hours - 12) + ':' + twoDigits(date.getUTCMinutes()) + ':' + twoDigits(date.getUTCSeconds()) + ' PM';
} else {
return strdate + twoDigits(hours) + ':' + twoDigits(date.getUTCMinutes()) + ':' + twoDigits(date.getUTCSeconds()) + ' AM';
};
};
console.log(formatDate("2020-10-01T17:00:00.000Z", true));
Here, you are constructing the time string from individual UTC segments. You could alternatively parse the input string using a regex, get the number of hours and then build the string that way.
Edit: updated to optionally also include the date, in US format mm/dd/yyyy.

Convert Current date in IST format using Javascript

I want to convert current date value to the below format using javascript
2019-08-23T08:23:47+0530
I had tried the following code
var currentTime = new Date();
var currentOffset = currentTime.getTimezoneOffset();
var ISTOffset = 330; // IST offset UTC +5:30
var ISTTime = new Date(currentTime.getTime() + (ISTOffset + currentOffset)*60000);
and also try to convert to toUTCString(). But any of them gives the desired format.
try this it will work for ISO date
Date.prototype.toIsoString = function() {
var timezone = -this.getTimezoneOffset(),
DF = timezone >= 0 ? '+' : '-',
pad = function(nm) {
var narmal = Math.floor(Math.abs(nm));
return (narmal < 10 ? '0' : '') + narmal;
};
return this.getFullYear() +
'-' + pad(this.getMonth() + 1) +
'-' + pad(this.getDate()) +
'T' + pad(this.getHours()) +
':' + pad(this.getMinutes()) +
':' + pad(this.getSeconds()) +
DF + pad(timezone / 60) +
'' + pad(timezone % 60);
}
var date = new Date();
alert(date.toIsoString())

Getting the date from Javascript comes up with bizarre values

I want to get the date and time in the following format:
yyyy.mm.dd.hh.mm.ss | 2014.11.6.20.31.24
However, my code (based on Get Current Time) is instead providing these values:
y??.m?.d?.hh.mm.ss | 114.10.4.20.31.24
Here is my code:
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getYear() + "." + dt.getMonth() + "." + dt.getDay();
alert(date + "." + time);
Can someone please let me know why these odd values are in there 114.10.4 and how to change them to be what I want?
That is because you need to use
.getFullYear() for the full year
the .getMonth() is 0-based so you need to add 1
the function to get the day of month is .getDate(). The .getDay() is for the day of the week.
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + (dt.getMonth()+1) + "." + dt.getDate();
alert(date + "." + time);
If, for some weird reason, you are going only for firefox, you can use
var d = new Date(),
formatted = d.toLocaleFormat('%Y.%m.%d.%H.%M.%S');
alert(formatted);
Finally, you can use the great moment.js library and do
var formatted = moment().format('YYYY.MM.DD.HH.mm.ss');
You are using the wrong getters. Use getFullYear() instead of getYear(), and getDate() instead of getDay(). And add 1 to the month, because it starts at 0.
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + (dt.getMonth() + 1) + "." + dt.getDate();
alert(date + "." + time);
Just make sure that you are using methods what you want to use e.g:
dt.getYear() => dt.getFullYear()
For further reference see this.
should use getFullYear() instead of getYear() and getMonth() + 1 instead of getMonth() because it calculate form 0..11 and info about getDay()
var dt = new Date();
var time = dt.getHours() + "." + dt.getMinutes() + "." + dt.getSeconds();
var date = dt.getFullYear() + "." + dt.getMonth() + 1 + "." + dt.getDate();
alert(date + "." + time);
dt.getDay() this day of the week
The getDay() method returns the day of the week (from 0 to 6)
You need to use getDate() to know the number of the day (from 1 to 31)
Also, you need to add 1 to getMonth() because months in JavaScript starts on 0

How to parse Date from JSON

I am using a grid view which is getting bind by json also on some conditions and a coloum of grid contains date , so while getting data from json, I need to parse the date. I am able to get date but not time part . Tried and searched too much . I am mentioning below two methods that I tried but not solves my problem.
{
function ParseDate(jsonDate) {
date = new Date(parseInt(String(jsonDate).substr(6)));
day = date.getDate();
month = date.getMonth() + 1;
year = date.getFullYear();
return month + "/" + day + "/" + year;
}
}
This gives me only date but I need time, so I did one more method
{
function ParseDate(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var formatted = ("0" + (date.getMonth() + 1)).slice(-2) + "/" + ("0" + date.getDate()).slice(-2) + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + "0" + date.getSeconds();
return formatted;
}
}
but this function returns
//07/19/2013 11:38
instead of //7/19/2013 11:38:07 AM which is desired result.Please help me solving this problem. Thank You very much. Also , I need to show Am or PM that is compulsory
Try this:
function ParseDateToLocale(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var myDate = new Date(date);
var formatted = myDate.toLocaleString();
return formatted;
}
See it working here: http://jsfiddle.net/2ft3A/.
Try this one, this will help you,
function ParseDate(jsonDate) {
var date = new Date(parseInt(jsonDate.substr(6)));
var merd='';
if(date.getHours()>=12)
{
merd='PM';
}
else
{
merd='AM';
}
var formatted = ("0" + (date.getMonth() + 1)).slice(-2) + "/" + ("0" + date.getDate()).slice(-2) + "/" + date.getFullYear() + " " + date.getHours() + ":" + date.getMinutes() + ":" + "0" + date.getSeconds()+ " " + merd;
return formatted;
}
dateObject.toLocaleTimeString(); (OR) date.getHours() will return 0-24hrs. Base on that value you can append AM or PM

using date in javascript

I have trouble using date in Javascript, in PHP you use something like date("Y-m-d H:i s") to retrieve the specific date and time, how can I achieve this in Javascript? the getMonth() method only returns 1 digit, I really need them to be in 2 digits
Since I made comments on almost all answers, I'd better post my suggestion
DEMO
function pad(num) { return ("0"+num).slice(-2); }
function getDisplayDate() {
var date = new Date();
return date.getFullYear()+
"-"+pad(date.getMonth()+1)+
"-"+pad(date.getDate())+
" "+pad(date.getHours())+
":"+pad(date.getMinutes())+
":"+pad(date.getSeconds());
}
setInterval(function() {
document.getElementById("time").innerHTML=getDisplayDate();
},500);
why dont you add 0 before when you get <10
Try this :
function dateToYMD(date) {
var d = date.getDate();
var m = date.getMonth() + 1;
var y = date.getFullYear();
return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d) + ' ' + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
}
var d = new Date();
alert(dateToYMD(d));
This code is adjusted based on the pointers given by #mplungjan -- (credits to him please)
Also check out his solution, which is a better one for use with date digits.
var str = 10; // month-digit from getMonth()
function pad(val) {
return "0" + val;
}
var month = str < 10 ? pad(str) : str;
console.log(month);
you can year, minutes, etc from Date class. You can get 2 digits month using some trick like example below. e.g
Date.prototype.getLongMonth = function() {
var month = this.getMonth();
if (String(month).length == 1) month = '0'.concat(month);
return month;
}
var now = new Date();
var theDate = now.getFullYear() + '-' + now.getLongMonth() + '-' + now.getDate() + ' ' + now.getHours() + ':' + now.getMinutes() + ':' + now.getSeconds();
console.log(theDate); // result : 2013-02-17 12:41:2

Categories

Resources