Parse a date like 2012-11-07T00:00:00 - javascript

I get from my client a date in this format:
2012-11-07T00:00:00 (yyyy-mm-ddT00:00:00)
How can I parse it into a Date object?
My first option is:
getting the first 10 characters (2012-11-07)
split that by "-"
creating new Date(splitted[0],splitted[1],splitter[2])
I know that such a question is obvious and over-answered, not only in Stack Overflow, but I want to:
know a better practice WITHOUT any library, pure JS ( Date.parse() ? )
the same with a widely used date library / framework for nodeJS

var d = new Date('2012-11-07T00:00:00')

Related

How do I format a date using javascript? [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 5 years ago.
How do I format a date using javascript: for example, change "2018-10-25T15:00:00.000Z" to Sat, "10/25" ?
Please and thank you
Using toLocaleString you could do:
console.log(
(new Date())
.toLocaleString(
window.navigator.language,
{month:"2-digit",day:"2-digit",weekday: 'short'}
)
);
console.log(
(new Date())
.toLocaleString(
"zh-CN",
{month:"2-digit",day:"2-digit",weekday: 'short'}
)
)
Using toLacaleString will get you a string based on locale and as Rob pointed out in the comment; this may differ even in different browsers.
If you want to show the user a local string then this is good but if you want to automatically process that string it's better to use something else like milliseconds after epoch UTC.
The format you provided would suggest user only because it's unfit for automatic processing (there is no timezone or year).
Maybe you are trying to combine formatted string to show the user with something you need to process later. In that case I would advice you to use tuple (array) that contains both ms after epoch and user formatted string.
Anyway, if you want to mix up formatted for human consumption with automation then you can do the following:
var d = new Date();
["Sun","Mon","Tue","Wed","Thu","Fri","Sat"][d.getDay()]+", "+
new String("0"+(d.getMonth()+1)).slice(-2) + "/" +
new String("0"+d.getDate()).slice(-2)
Moment.js library could probably save you a lot of time with this tedious task:
moment(new Date('2018-10-25T15:00:00.000Z')).format("dddd, MM/D")
output:
"Thursday, 10/25"
You can mess around with it by opening the JS console on their docs page, as moment is loaded on it.
Edit- as noted in comments, if this is the only task you are using it for, probably best not to use a lib and do it in plain JS!

Managing multiple date formats in Javascript

Similar questions has been asked many times but I couldn't find a more concrete solution. The things I'm doing are:
I have a <input type="date"> inside my HTML which when clicked opens a calender with date in dd/mm/yyyy format.
I change the html5 date to timestamp to send to my db by Date.parse(html5Date) and in the server I modify the date and send it back to my Angular app.
I now convert the timestamp back to Date object by new Date(timestamp).To print the date in a human-friendly format inside a table I do [date.getDate(), date.getMonth() + 1, date.getFullYear()].join('/').
On edit (PUT request), I again capture the date from HTML, convert it to timestamp, send it to server and process the returning date back to html date.
Other than these, I also do a ton of functionalities like date comparison, adding hours to the dates, show time of the day etc inside the HTML:
Just these simple operations are over 120 lines of code which I think is ridiculous and error prone. I've looked into Angular Datepicker but it's a bit confusing. Also sometimes the HTML date is of type Object and sometimes it's String so Date.parse() gives error.
Are there any developer friendly methods that does : copy HTML5 date (from datepicker) --> change to timestamp (for angular&server) --> format timestamp back to string/object (for html)? Thank You :)
Note: Angular throws a lot of annoying error in console saying dateformat is wrong (being html date type) but doesn't stop code from running
Sounds like you are doing waaay to many conversions. I would argue that there should only be one way dates are represented: as Date objects in the programming language. There are only a few conversions that need to happen:
Date <=> Integer milliseconds since the epoch to pass to server
Date <=> String human-readable format to display to user
Any thing beyond this is asking for trouble. Comparisons can be made by casting to int date.getTime(), comparing, and casting back to Date. Ditto for additions. Note that Date.parse is implementation dependent in what it will accept, although all of them will accept ISO 8601 formatted date strings anything else is guesswork. Which means you will have to deal with converting strings by hand, something like the following:
var toDate = str => {
var splitter = str.indexOf("/") === -1 ? "-" : "/";
var [mon, day, year] = str.split(splitter);
return new Date(year, mon - 1, day);
};
var toDateString = date => {
return "" + date.getFullYear() + (date.getMonth() + 1) +...
};
Note that there's no validation, that's left as an exercise to the reader.
A WORD ABOUT MOMENT.JS
moment.js is awesome. Its also huge, its a kitchen-sink API with a heft to match. You're already loading angular, so think carefully before bulking the size of your payload with another huge library.
Moment.js is a powerful date formatting and manipulation library. A lot of things you can do in Moment.js are a single line of code, which makes life a lot easier. I agree, without using a library like this date formatting and handling can be a pain.
http://momentjs.com/
EDIT: fyi, I use this with my Angular app and find it extremely useful!

How to parse date time in JavaScript

I have Date in this format mm/dd/yy example: 04/11/13
and time in the format HH:MM:SS example: 17:02:30
I have to parse above two values and put in a variable dateTime with following format
YYYY-MM-DDTHH:MM:SSS
2013-04-11T17:02:30.000
What is best way to do it in AngularJS or in Javascript. I also need to verify the user input and make sure it is a valid mm/dd/yy date and a valid HH:MM:SS time
I know there are tons of duplicate/similar questions but I couldn't find one which answers above, please let me know if you found one.
You don't need an external library to do this. See this doc link for the forms of date that JavaScript can process normally.
For a specific solution to your question:
var date = new Date("04/11/13" + " " + "17:02:30");
date.toISOString();
>> "2013-04-11T21:02:30.000Z"
See this MDN page for more info on the Date object.
The best way to do this in AngularJS is with a filter. You bind to the dateTime, and then filter it with the date filter.
<span>{{myDate | date:yyyy-MM-ddThh:mm:sss}}</span>
Or in your controller you say:
$filter('date')(date[, format])
Here is more info: http://docs.angularjs.org/api/ng.filter:date

JavaScript date() Object returns NaN with getYear (and other)

I am currently having some issues converting a string dateTime object in JavaScript
I am assuming it is because my string cannot me used properly in a new Date() but I'm not sure that is the problem.
My Input: "2011-09-29 14:58:12"
My code:
var date = "2011-09-29 14:58:12";
var added = new Date(date);
var year = added.getYear();
However, my year var contains NaN. Same with getDay() or getMonth(). What is the problem?
ps: I'm getting the date in it's format from a SQLite database. And I'm using Titanium Mobile, so javascript and SQLite are the only things involved
You're relying on the Date constructor parsing an unsupported format. Until recently, there was no standard string format supported by the Date constructor. As of ECMAScript5, there is one (YYYY-MM-DDTHH:MM:SS, note the T rather than space), but it's only been specified for just under two years and naturally doesn't work in older browsers.
For the time being, your best bet is to parse it yourself (you can find code in this question and its answers), or use something like DateJS, MomentJS, date-fns, etc. to parse it for you.
The Date constructor will not parse a string for you. You'll need to use Date.parse to do that. Interestingly enough, Date.parse doesn't actually return a Date. Instead it returns a unix timestamp. You can then pass the unix timestamp into the Date constructor to get what you're looking for.
var d = new Date(Date.parse("2011-09-29 14:58:12"));

Converting json results to a date [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to format a JSON date?
I have the following result from a $getJSON call from JavaScript. How do I convert the start property to a proper date in JavaScript?
[
{"id":1,"start":"/Date(1238540400000)/"},
{"id":2,"start":"/Date(1238626800000)/"}
]
Thanks!
You need to extract the number from the string, and pass it into the Date constructor:
var x = [{
"id": 1,
"start": "\/Date(1238540400000)\/"
}, {
"id": 2,
"start": "\/Date(1238626800000)\/"
}];
var myDate = new Date(x[0].start.match(/\d+/)[0] * 1);
The parts are:
x[0].start - get the string from the JSON
x[0].start.match(/\d+/)[0] - extract the numeric part
x[0].start.match(/\d+/)[0] * 1 - convert it to a numeric type
new Date(x[0].start.match(/\d+/)[0] * 1)) - Create a date object
I use this:
function parseJsonDate(jsonDateString){
return new Date(parseInt(jsonDateString.replace('/Date(', '')));
}
Update 2018:
This is an old question. Instead of still using this old non standard serialization format I would recommend to modify the server code to return better format for date. Either an ISO string containing time zone information, or only the milliseconds. If you use only the milliseconds for transport it should be UTC on server and client.
2018-07-31T11:56:48Z - ISO string can be parsed using new Date("2018-07-31T11:56:48Z") and obtained from a Date object
using dateObject.toISOString()
1533038208000 - milliseconds since midnight January 1, 1970, UTC - can be parsed using new Date(1533038208000) and obtained from a Date object
using dateObject.getTime()
If you use jQuery
In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON() function to automatically convert dates for you.
You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON(), but if you start using $.parseJSON(data, true), dates in data string will be automatically converted to Javascript dates.
It supports Asp.net date strings: /Date(2934612301)/ as well as ISO strings 2010-01-01T12_34_56-789Z. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).
Anyway. Head over to blog post to get the code.
http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html
If that number represents milliseconds, use the Date's constructor :
var myDate = new Date(1238540400000);

Categories