Javascript date string conversion - javascript

I have a system that returns a JSON object that contains dates in string format.
These dates are in the format "2012-10-19 06:05:38 GMT" (no... I'm stuck with them like this)
So I need to get this into a date object (d) ready to output as d.toLocaleDateString()
In chrome it works perfectly by just passing the string to a new Date (Bad bad Chrome - makes Eric lazy), but of course it fails in FF and IE
I can fix it by splitting the string but its not pretty and I've not figured out dealing with the offsets from GMT.
There must be a more elegant way...?
I'm sure someone here can do it in one line.

It's not quite a one-liner, but if you know all your dates will be GMT, something like the following should work:
function parseDate(dateString) {
// [y, m, d, hr, min, sec]
var parts = dateString.match(/\d+/g);
// Months are 0-indexed
parts[1] -= 1;
return new Date(Date.UTC.apply(Date, parts));
}

If I were you, and had access to the serverside script gathering that information (and outputting it) I would convert the date into a unix timestamp, and then make Javascript process that using the Date constructor easily.
EDIT: You can use strtotime() function to convert the string date into numeric unix timestamp if you're using PHP.

If you know the exact format, you could use a library such as Moment.js: Documentation for Moment.js.
To parse:
var dateString = "2012-10-19 06:05:38 GMT".replace(" GMT", "");
var date = moment(dateString, "YYYY-MM-DD HH:mm:ss");

You can just parse the dateString manually,and pass the Date the Date constructor exactly:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
var dateString = "2012-10-19 06:05:38 GMT".split(" "),
date = dateString[0].split("-"),
time = dateString[1].split(":");
var dateObj = new Date(date[0],date[1]-1,date[2],time[0],time[1],time[2]);

Related

Get "Day" From This Formatted Timestamp In Javascript

I'm working with Javascript within Google Sheets, and I'm having trouble converting or parsing a formatted timestamp, to ultimately extract the day as a numerical value.
My code:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
Logger.log(date.getDay());
The output:
[19-06-10 17:40:56:107 BST] NaN
My goal is to extract the day number, for example, "18" from that timestamp.
However, it doesn't seem to convert it. I suspect my timestamp isn't in the correct format for the date() function, so it's about creating a function to parse it.
Hopefully, you can help me with that! :) Thank you so much.
The date object has a method like this for getting the day of the month as a number (1-31).
date.getDate();
18 is date.
var shopifyTimestamp ="2019-05-18 13:21:17 +0100";
var date = new Date(shopifyTimestamp);
console.log(date.getDate());
JavaScript's Date constructor supports ISO 8601 date strings. Without using any libraries, you can do something like this:
var shopifyTimestamp = "2019-05-18 13:21:17 +0100";
// will produce `2019-05-18T13:21:17+0100`
var isoDate = shopifyTimestamp.slice(0, 10)
+ 'T' + shopifyTimestamp.slice(11, 19)
+ shopifyTimestamp.slice(20);
var date = new Date(isoDate);
console.log(date.getDate()); // 18
Also note that you're looking for date.getDate(), rather than date.getDay(). The latter returns the numerical date of the week.

Converting funky datetime using Apps Script .toISOString() method

I've got a column of datetimes in the following funky format:
2016-07-07 12:34:47 -0700
I understand that I can convert this to a usable format by using the .toISOString() function in JS/Apps Script.
Not to be presumptuous, but can anybody easily manage this feat, help me take the first step, or even point me in the direction perhaps of a published Apps Script that can do this?
Thanks so much :)
Return the Date object as a string, using locale conventions:
var d = new Date();
var n = d.toLocaleDateString();
Convert today's date into a readable string:
var d = new Date();
var n = d.toDateString();
Other functions that might be useful:
.toUTCString()
.toString()

how can i convert a date like dd-mm-yyyy into ISO date format, to store in a mongoDB

In my mean stack app, i have data on a date basis. In angular side, i used a date picker to get/set the date that the read/write of Data to be handled. The date picker produce date of the form "dd-mm-yyyy". What is the easiest way to convert this into mongodb understandable format, and back.
var str = "29-1-2016";
darr = str.split("-"); // ["29", "1", "2016"]
var dobj = new Date(parseInt(darr[2]),parseInt(darr[1])-1,parseInt(darr[0]));
// Date {Fri Jan 29 2016 00:00:00 GMT+0530(utopia standard time)
console.log(dobj.toISOString());
//2016-01-28T18:30:00.000Z
This will do it, but is there an easier way..!!
Also please comment on why in the isodate format i get 2016-01-28T...., other than 2016-01-29T.....
You could use this solution (worked in my case)-
Firstly, use Moment.js in your code, include it in your project. Now, The time string that you are getting here var str = "29-1-2016"; and along with moment.js use the below code and you're good to go -
var str = "29-1-2016";
var time = moment(str).toISOString();
\\ This variable time is now converted into ISO string

Issue with javascript date object

I am facing a weird problem while initializes javascript date object,no matter what I initialize to it shows the date as 1 JAN 1970 05:30;
this is the way I try to initialize
var d=new date(27-02-1989);
alerting 'd' shows 1 JAN 1970.....,also sometimes it takes a date passed from the database but in the format as mm/dd/yyyy not in the format I want i.e dd/mm/yyyy
This problem has suddenly popped-up, as everything was working smooth couple of days ago,but today after opening the project (after 2 days) this issue is irritating me
I see you've accepted an answer, but it isn't the best you can do. There is no one format that is parsed correctly by all browsers in common use, the accepted answer will fail in IE 8 at least.
The only safe way to convert a string to a date is to parse it, e.g.
var s = '27-02-1989';
var bits = s.split('-');
var date = new Date(bits[2], --bits[1], bits[0]);
// Transform your european date in RFC compliant date (american)
var date = '27-02-1989'.split('-').reverse().join('-');
// And this works
var d = new Date( date );
Proof:
You're doing an initialization with a negative integer value (27-02-1989 == -1964). The Date object's constructor takes arguments listed here.
If you want to pass strings, they need to be in an RFC2822-compliant format (see here).
according to here you can try:
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day [, hour, minute, second, millisecond ])
so for your case use (edit: You need to remember that months are zero based)
var d = new Date(1989,01,27);
pleas notice - use Date (capital D)
First of all
var d=new date(27-02-1989);
is totaly wrong expression in javascript, moreover even if we rewrites it more correctly:
var d=new Date('27-02-1989');
there is no way to parse this date string natively in js.
Here solutions you can try:
transform string to ISO8601: YYYY-mm-dd, this can be parsed by most modern broswers, or you can use many js libraries for polyfill
split string string by '-' and then use Date constructor function new Date(year, month-1, day)
split string and use setDate, setMonth, setYear method on new Date() object
Note that in last two methods you need to deduct 1 from month value, because month is zero-based (0 stands for January, 11 for December)

Is there a simple conversion for this datetime format?

I'm retrieving data from a JSON feed using jQuery and as part of the feed I'm getting 'datetime' attributes like "2009-07-01 07:30:09". I want to put this information into a javascript Date object for easy use but I don't believe the Date object would recognize this kind of format if I simply plugged it into the constructor. Is there a function or maybe a clever trick I can use to quickly break down this format into something the Date object can recognize and use?
The "date" attribute you are retrieving from that webservice is not a real Date, as it is not a recognized date format.
The easiest way to handle it as a Date object would be to replace the empty space with a "T":
var receivedDate = "2009-07-01 07:30:09";
var serializedDate = new Date(receivedDate.replace(" ", "T"));
alert(serializedDate);
This is not the most correct, as it is not handling timezones, but in most cases will work.
See this and this.
input = "2009-07-01 07:30:09";
var res = input.match(/([\d\-]+) (\d+):(\d+):(\d+)/);
date = new Date(Date.parse(res[1]));
date.setHours(res[2]);
date.setMinutes(res[3]);
date.setSeconds(res[4]);
console.log(date);
Edit: My original answer was
t = new Date(Date.parse("2009-07-01 07:30:09"));
which did not throw any error in chrome but all the same incorrectly parsed the date. This threw me off. Date.parse indeed appears to be quite flaky and parsing the complete date and time with it is probably not very reliable.
Edit2: DateJS appears to be a good solution for when some serious parsing of text to date is needed but at 25 kb it is a bit heavy for casual use.
var str="2009-07-01 07:30:09";
It depends on the time zone,
and if the date string has subtracted 1 for the month.
If it is GMT time, and the 07 means July and not August:
var str="2009-07-01 07:30:09";
var d=new Date(), time;
str=str.split(/\D0?/);
str[1]-=1;
time=str.splice(3);
d.setUTCFullYear.apply(d,str);
d.setUTCHours.apply(d,time)
alert(d)
/* returned value: (Date)
Wed Jul 01 2009 03:30:09 GMT-0400 (Eastern Daylight Time) or local equivilent
*/
This may be a bit cumbersome, but the JavaScript Date object will take an argument list of YYYY,MM,DD,HH,MM,SS. Parse out the date value and pass it to a Date constructor, e.g.
var splitDT= '2009-07-01 07:30:09'.split(' '); // ['2009-07-01','07:30:09']
var d= splitDT[0].split('-');
var t= splitDT[1].split(':');
alert( (new Date(d[0],d[1],d[2],t[0],t[1],t[2])) );
Bah. Had to use the array index values instead. Yeah, that's a mess. But it works.

Categories

Resources