I have a date string in format dd/MM/yyyy and I want to create a Date object from this string. new Date(dd/MM/yyyy)
won't work..
I have this code, that obviously does not work:
function createDateObject(value){
try{
return new Date(value.split('/').**swap(0, 1)**.join('/'));
}
catch(){
return null;
}
}
createDateObject('31/01/2014') => Fri Jan 31 2014 00:00:00 GMT-0200 (Local Daylight Time)
Which is the simplest way to do this?
I wouldn't like to create a lot of temp variables if I could do it in one single line...
Since your question is how to swap month with day in a string (dd/mm/yyyy
to mm/dd/yyyy
), this is the answer:
var dateString = "25/04/1987";
dateString = dateString.substr(3, 2)+"/"+dateString.substr(0, 2)+"/"+dateString.substr(6, 4);
However, if you would like to create a new Date()
object, you have to change the string according to the ISO 8601 format (dd/mm/yyyy
to yyyy-mm-dd
):
var dateString = "25/04/1987";
dateString = dateString.substr(6, 4)+"-"+dateString.substr(3, 2)+"-"+dateString.substr(0, 2);
var date = new Date(dateString);
How about this?
value = value.split("/");
var d = new Date(value[2], parseInt(value[1], 10)-1, value[0]);
You have to subtract 1
from month because JavaScript counts months from 0
.
Thanks to CBroe I used Array.reverse
and it worked with my test cases.
Just replaced **swap with reverse():
function createDateObject(value) {
try {
return new Date(value.split('/').reverse().join('/'));
}
catch(e) {
return null;
}
}
It creates the Date correctly, but let invalid dates to be created, such as Feb/30/2014.
So I also have to validate string using this Answer:
function createDateObject(value) {
try {
string formatted = value.split('/').reverse().join('/');
return isValidDate(formatted) ? new Date(formatted) : null;
} catch(e) {
return null;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With