Get GMT String from current Date - javascript

I am able to get the output format that I need, but not the correct time. I need it in GMT (which is +4 hours)
var dt = new Date();
var dt2 = dt.toString('yyyyMMddhhmmss');
Any ideas? The output looks like:
20120403031408
I am able to get the GMT in standard string format by doing:
dt.toUTCString();
but im unable to convert it back to the yyyyMMddhhmmss string
EDIT: I am using the date.js library

date.js's toString(format) doesn't have an option to specify "UTC" when formatting dates. The method itself (at the bottom of the file) never references any of Date's getUTC... methods, which would be necessary to support such an option.
You may consider using a different library, such as Steven Levithan's dateFormat. With it, you can either prefix the format with UTC:, or pass true after the format:
var utcFormatted = dateFormat(new Date(), 'UTC:yyyyMMddhhmmss');
var utcFormatted = dateFormat(new Date(), 'yyyyMMddhhmmss', true);
// also
var utcFormatted = new Date().format('yyyyMMddhhmmss', true);
You can also write your own function, as Dominic demonstrated.

The key is to use the getUTC functions :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
/* 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();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z

Related

Combine date formatting vars and functions (jquery/Javascript)

I have a bit of javascript that gets different date ranges and formats them to return yyyymmdd. I get the final result I need, but something about having 2 different variables bugs me and makes me think I am not doing this the best way. I am wondering if there is a way to pass the new date and the additional removal of - all in one line.
my function is:
function toJSONLocalMonth (firstDay, lastDay) {//set default date range to from beggining of this month
var local = new Date(firstDay);
local.setMinutes(firstDay.getMinutes() - firstDay.getTimezoneOffset());
return local.toJSON().slice(0, 10);
var local = new Date(lastDay);
local.setMinutes(lastDay.getMinutes() - lastDay.getTimezoneOffset());
return local.toJSON().slice(0, 10);
}
And whenever I need the result I do this:)example of today and yesterday)
var dateToday = new Date();
dateTodayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");//format date yyyymmdd
dateYesterday = dateToday.setDate(dateToday.getDate() - 1);
dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");
If there a better way to get this result, or at the very least combine the dateYesterday and dateYesterdayFormat to a single line to get yyymmdd.
(I need to keep the - in the function result, so I can't filter it there.)
Thanks!
Your question is unclear.
toJSONLocalMonth will only return one value, the one from the first return statement. The second is never reached.
The return value from dateToday.setDate(...) is a time value (a number), not a Date so you can't chain a string method to it. It modifies the date itself so dateYesterday is redundant, i.e.
dateYesterday = dateToday.setDate(dateToday.getDate() - 1);
dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");
can be:
dateToday.setDate(dateToday.getDate() - 1);
var dateYesterdayFormat = toJSONLocalMonth(dateToday).replace(/-/g, "");
The toJSONLocalMonth seems to be just getting a date string formatted as YYYYMMDD. I guess you're avoiding the built–in ISO methods because they use UTC/GMT and not the local time zone. The following function does that in a more obvious way:
/* Return an ISO 8601 formatted date string
** #param {Date} d - date to create string for
** #returns {string} string formatted as ISO 8601 without timezone
*/
function toISOStringLocal(d) {
function z(n){return (n<10?'0':'') + n}
return d.getFullYear() + '-' + z(d.getMonth()+1) + '-' +
z(d.getDate()) + 'T' + z(d.getHours()) + ':' +
z(d.getMinutes()) + ':' + z(d.getSeconds())
}
console.log(toISOStringLocal(new Date));
You might also consider a small formatting library like fecha.js where you'd do:
var dateToday = new Date();
var dateTodayFormat = fecha.format(dateToday, 'YYYYMMDD')
dateToday.setDate(dateToday.getDate() - 1);
var dateYesterdayFormat = fecha.format(dateToday, 'YYYYMMDD');
The last two lines could become one using:
var dateYesterdayFormat = fecha.format(new Date(dateToday.setDate(dateToday.getDate() - 1)), 'YYYYMMDD');
but I wouldn't recommend that.
Also see: Where can I find documentation on formatting a date in JavaScript?

Javascript Date String returns invalid Date

I am trying to convert a date string into a date object within javascript. My date has the following format:
"13.02.2015 12:55"
My current approach was:
var d = new Date("13.02.2015 12:55");
But this didnt work and always returns invalid date. If I enter a date as "12.02.2015 12:55" it works in chrome but not in firefox.
I guess this is because he thinks the first part is the month, but in germany this is not the case.
How can I get this to work?
use moment.js:
var date = moment("13.02.2015 12:55", "DD.MM.YYYY HH.mm").toDate();
Update 2022-05-28:
Meanwhile the project status of moment.js has changed. Therefore I strongly suggest to read https://momentjs.com/docs/#/-project-status/ and observe the recommendations.
try the ISO 8601 format,
or better yet, read this http://www.ecma-international.org/ecma-262/5.1/#sec-15.9
Edit: if you have no other choice than to get it in that format though, i guess you'll need something like this:
function DDMMYYYY_HHMMtoYYYYMMDD_HHMM($DDMMYYYY_HHMM) {
var $ret = '';
var $foo = $DDMMYYYY_HHMM.split('.');
var $DD = $foo[0];
var $MM = $foo[1];
var $YYYY = $foo[2].split(' ') [0].trim();
var $HH = $foo[2].split(' ') [1].split(':') [0].trim();
var $MMM = $foo[2].split(' ') [1].split(':') [1].trim();
return $YYYY + '-' + $MM + '-' + $DD + ' ' + $HH + ':' + $MMM;
}
var d=new Date(DDMMYYYY_HHMMtoYYYYMMDD_HHMM('13.02.2015 12:55'));

Display the Local Date and Time as Year-Month-Day Hour-Minute-Second in JavaScript

I am trying to create a variable that holds a formatted date display in JavaScript. What I want is for the value to be set as Year-Month-Day Hour-Minute-Second. So far this is what I have.
The toJSON method changes the timezone and I want it to represent my local time. That is why I added the getTimezoneOffset code.
var date = new Date(Date.now() - (new Date().getTimezoneOffset() * 1000 * 60)).toJSON().replace(/T/, ' ').replace(/:/g, '-').split('.')[0];
console.log(date); // 2014-05-23 22-24-26
Is there a simpler or more appropriate way to get this value?
You may try toLocaleString(), for example:
var d = new Date().toLocaleString(); // 5/24/2014 3:11:16 AM
But to format the date you may try something like this (or other ways):
var d, t;
d = new Date();
d = (d.toLocaleString()).split(' ');
t = d[1];
d = d[0].split('/');
d = d[2] + '-' + d[1] + '-' + d[0] + ' ' + t;
You may like this.
Yep, I like to use MomentJS for dealing with the many issues with JavaScript dates and times. It allows you to:
moment() //now, whatever the local time is
.format('YYYY-MM-DD HH-mm-ss') // "2014-05-23 21-48-11"
Simples :)

How to format a date pulled from a form field with javascript

I have a date picker that generates a date like 6/30/2012 in a form field.
I need to convert this date to 2012-06-30 for mysql. I can get it close with the following.
var datePart=document.getElementById('formdate').value.split(/[^0-9]+/);
and then use to generate the date.
datePart2[2] + "-" + datePart2[1] + "-" + datePart2[0]
The problem is it gived me the date 2012-6-30 instead of 2012-06-30.
Is there an easier way to do this? Or a way to use my current method and ad a zero to the front of a digit if it is a single digit?
The Open Source date.js ( http://www.datejs.com/ )provides a really extensive framework for JavaScript dates, IMHO superior to the jQuery plug-in. It may be more than you need for this requirement, but I think it is a welcome addition to any JavaScript programmers's arsenal.
To format your example:
var mySqlDate = Date.parse('6/30/2012').toString('yyyy-MM-dd');
Are you using jQuery? if so you could use the Date Format plugin, makes date manipulation easy
http://archive.plugins.jquery.com/project/jquery-dateFormat
try this, hope this help:
Format date in jquery- from Sat Mar 03 2012 14:16:05 GMT+0530 to 03/03/2012
important you need to put a check condition like this one and if its less then 10 append 0 [code] date < 10 ? "0"+date : date; cheers!
something on the line of this:
function dateFormatFoo(){
var d = new Date();
date = d.getDate();
date = date < 10 ? "0"+date : date;
mon = d.getMonth()+1;
mon = mon < 10 ? "0"+mon : mon;
year = d.getFullYear()
return (date+"/"+mon+"/"+year);
}
Based on your example, a simple function is:
var formatUStoISOdate = (function() {
function aZ(n) {
return (n<10? '0' : '') + n;
}
var re = /[^0-9]/;
return function(d) {
var d = d.split(re);
return d[2] + '-' + aZ(d[0]) + '-' + aZ(d[1]);
// or
// return [d[2], aZ(d[0]), aZ(d[1])].join('-');
}
}());
alert(formatUStoISOdate('3/31/2011')); // 2011-03-31

Javascript date question about format

I've been struggling with javascript more than an hour and came up with a solution - to ask you for help!
A RSS Feed generates the date of every post in this format 2011-05-18T17:32:43Z. How can I make it look like that 17:32 18.05.2011?
Thank you in advance!
Assuming you've parsed the RSS date into a JS Date object (which can be tricky, since many Date.parse implementations don't accept ISO-8601 dates like that)...
//var d=new Date(/*...*/)
// 17:32 18.05.2011
pad(d.getHours())+':'+d.getMinutes()+' '+
pad(d.getDate())+'.'+pad(d.getMonth()+1)+d.getFullYear();
(getMonth returns 0-11 based month)
... you'd also want some kind of zero buffering for the month (in your example) and possibly day, hour (depending)....
function pad(val,len) {
var s=val.toString();
while (s.length<len) {s='0'+s;}
return s;
}
Optionally from string->string you could use:
function reformat(str) {
var isodt=string.match(/^\s*(\-?\d{4}|[\+\-]\d{5,})(\-)?(\d\d)\2(\d\d)T(\d\d)(:)?(\d\d)?(?:\6(\d\d))?([\.,]\d+)?(Z|[\+\-](?:\d\d):?(?:\d\d)?)\s*$/i);
if (isodt===null) {return '';} // FAILED
return isodt[5]+':'+isodt[7]+' '+isodt[4]+'.'+isodt[3]+'.'+isodt[1];
}
You can create a new Date, get the fragments out of it and concatenate everything:
function parse(date) {
var d = new Date(date)
return d.getHours() + ":" + d.getMinutes()
+ " " + d.getDate() + "." + (d.getMonth()+1)
+ "." + d.getFullYear();
}

Categories