I have problem with convert date which I get from API. Format is for example "16/09/25"
I try do it like this
var x = new Date(dateFromApi)
and console thorw me error.
3 Answers
Parsing a date string is very simple. A function that will work in any host from IE 4 onward is:
function parseDMY(s) {
var b = s.split(/\D/);
return new Date(b[2], b[1]-1, b[0]);
}
console.log(parseDMY('16/09/25'));
Where the year is >= 0 or <= 99, 1900 is added so 25 becomes 1925. Preserving years in this range (so 25 is 0025) requires an additional line of code.
Comments
It is safest to provide the Date constructor with the individual parts of the date (i.e., year, month and day of the month).
In ES6 you can provide those elements like this:
var x = new Date(...dateFromApi.split('/').reverse().map( (p,i) => p-(i%2) ));
The map is needed to subtract one from the month number, as it should be zero-based in numeric format.
Note the new Date(year, month, day) version of the constructor will assume 19xx when you provide only 2 digits.
var dateFromApi = "16/09/25"
var x = new Date(...dateFromApi.split('/').reverse().map( (p,i) => p-(i%2) ));
console.log(x.toDateString());
In ES5, it would be a bit longer, like this:
new (Date.bind.apply(Date, (dateFromApi+'/').split('/').reverse()
.map(function (p,i) { return p-(i==2); })));
var dateFromApi = "16/09/25"
var x = new (Date.bind.apply(Date, (dateFromApi+'/').split('/').reverse()
.map(function (p,i) { return p-(i==2); })));
console.log(x.toDateString());
Of course, this assumes that the input format is consistently in the order DD/MM/YY (or D/MM/YYYY, as long as the order is the same); that valid dates are passed, and that you accept how 2-digit years are mapped to 4-digit years.
7 Comments
new Date(year, month, day) JavaScript will assume 19xx when you provide only 2 digits for the year part.momentjs offers most of what date manipulation tasks call for.Your format is DD/MM/YY and it is not accepted by Date and will throw an error.
This is because, as mentioned by @MattJohnson, the accepted Date formats vary by locale and the only official format is YYYY-MM-DD (which is derived from ISO date string. Read here).
In most cases, Date will accept the format YY-MM-DD. So we can simply do this:
var date = "16/09/25"; // date received from API
var split_date = date.split('/'); // outputs ["16","09",""25"]
var rearranged_date = [split_date[1], split_date[0], split_date[2]].join('/'); // outputs "09/16/25"
var proper_date = new Date(rearranged_date);
In other cases, it is best to provide the full-year YYYY instead of just YY.
2 Comments
MM/DD/YY everywhere. It varies by locale of the user. The only input format required by the spec is YYYY-MM-DD, which will also be interpreted as UTC. Basically, string parsing of dates is implementation dependent, and locale sensitive.
YYYYfrom API?