That's the best and simpler solution in my view:
Just concatenate your date string [using ISO format] with "T00:00:00" in the end and use the JavaScript Date[] constructor, like the example below.
const dateString = '2014-04-03'
var mydate = new Date[dateString + "T00:00:00"];
console.log[mydate.toDateString[]];
And just a few details about the solution above [but optional reading]:
In ISO format, if you provide time and Z is not present in the end of string, the date will be local time zone instead of UTC time zone. That means, when setting a date in this way, without specifying the time zone, JavaScript will use the local browser's time zone. And when getting a date, without specifying the time zone as well, the result is also converted to the browser's time zone. And, by default, almost every date method in JavaScript [except one] gives you a date/time in local time zone as well [you only get UTC if you specify UTC]. So, using in local/browser time zone you probably won't get unwanted results because difference between your local/browse time zone and the UTC time zone, which is one of the main complaints with date string conversion. But if you will use this solution, understand your context and be aware of what you are doing. And also be careful that omitting T or Z in a date-time string can give different results in different browsers.
Important to note that the example above will give you exactly the same return to this example below, that is the second most voted answer in this question:
var parts ='2014-04-03'.split['-'];
// Please pay attention to the month [parts[1]]; JavaScript counts months from 0:
// January - 0, February - 1, etc.
var mydate = new Date[parts[0], parts[1] - 1, parts[2]];
console.log[mydate.toDateString[]];
The main difference is that the first example provided here is simpler and even more error proof than the second one [at least in my view, as explained below].
Because if you call the JavaScript Date[] constructor date with just one date-string argument in ISO format [first example], it doesn't accept values above its logical limit [so, if you give 13 as month or 32 as day, you get Invalid Date].
But when you use the same constructor with multiple date-arguments [second example], parameters above it logical limit will be adjusted to the adjacent value and you won't get Invalid Date Error [so, if you give 13 as month, it will adjust to 1, instead of give you an Invalid Date].
Or an alternative [and third] solution would be mix both, use the first example just to validate the date-string and if it is valid use the second example [so you avoid possible browsers inconsistences of the first example and at the same time avoid the permission of parameters above it logical limit of the second example].
Like so [accepting partial dates as well]:
function covertStringToDate[dateString] {
//dateString should be in ISO format: "yyyy-mm-dd", "yyyy-mm" or "yyyy"
if[new Date[dateString].toString[] === "Invalid Date"] {
return false
} else {
const onlyNumbers = dateString.replace[/\D/g, ""];
const year = onlyNumbers.slice[0,4]
const month = onlyNumbers.slice[4,6]
const day = onlyNumbers.slice[6,8]
if[!month]{
return[new Date[year]]
} else if [!day] {
return[new Date[year, month - 1]]
} else {
return[new Date[year, month - 1, day]]
}
}
}
And a fourth alternative [and last suggestion] would be to use an appropriate third library [like moment or date-fns]
References:
- //www.w3schools.com/js/js_date_formats.asp
- //css-tricks.com/everything-you-need-to-know-about-date-in-javascript/
- //developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date#parameters
Convert a String to a Date object in JavaScript #
Use the Date[]
constructor to convert a string to a Date
object, e.g. const date = new Date['2022-09-24']
. The Date[]
constructor takes a valid date string as a parameter and returns a Date
object.
Copied!
const str = '2022-09-24'; const date = new Date[str]; console.log[date]; // 👉️ Sat Sep 24 2022
We used the
Date[] constructor to convert a string to a Date
object.
If you get an invalid Date when creating the Date
object, you need to format the string correctly before passing it to the Date[]
constructor.
If you have difficulties creating a valid Date
object, you can pass 2 types of arguments to the
Date[]
constructor:
- a valid ISO 8601 string, formatted as
YYYY-MM-DDTHH:mm:ss.sssZ
, or justYYYY-MM-DD
, if you only have a date without time. - multiple, comma-separated arguments that represent the
year
,month
[0 = January to 11 = December],day of the month
,hours
,minutes
andseconds
.
Here is an example that splits an MM/DD/YYYY
formatted string [could be any other format] and passes the values as arguments to the Date[]
constructor to create a Date
object.
Copied!
const str = '09/24/2022'; const [month, day, year] = str.split['/']; console.log[month]; // 👉️ 09 console.log[day]; // 👉️ 24 console.log[year]; // 👉️ 2022 const date = new Date[+year, +month - 1, +day]; console.log[date]; // 👉️ Sat Sep 24 2022
We split the date
on each forward slash to get the values for the month, day and year.
Notice that we subtracted 1
from the month when passing it to the Date[]
constructor.
This is necessary because the Date
constructor expects a zero-based value for the month, where January = 0, February = 1, March = 2, etc.
Here is another example, which creates a Date
that also contains the hours, minutes and seconds.
Copied!
const str = '09/24/2022 07:30:14'; const [dateValues, timeValues] = str.split[' ']; console.log[dateValues]; // 👉️ "09/24/2022" console.log[timeValues]; // 👉️ "07:30:14" const [month, day, year] = dateValues.split['/']; const [hours, minutes, seconds] = timeValues.split[':']; const date = new Date[+year, +month - 1, +day, +hours, +minutes, +seconds]; // 👇️️ Sat Sep 24 2022 07:30:14 console.log[date];
We first split the date and time string on the space, so we can get the date and time components as separate strings.
We then had to split the date string on each forward slash to get the value for the month, day and year. Note that your separator might be different, e.g. a hyphen, but the approach is the same.
We also split the time string on each colon and assigned the hours, minutes and seconds to variables.
We then passed all of the
values to the Date[]
constructor to create a Date
object.
If you need to store a date string in your database, it's best to store the ISO 8601 representation of the date.
You can get the ISO formatted date by calling the toISOString[]
method.
Copied!
const str = '09/24/2022 07:30:14'; const [dateValues, timeValues] = str.split[' ']; console.log[dateValues]; // 👉️ "09/24/2022" console.log[timeValues]; // 👉️ "07:30:14" const [month, day, year] = dateValues.split['/']; const [hours, minutes, seconds] = timeValues.split[':']; const date = new Date[+year, month - 1, +day, +hours, +minutes, +seconds]; // 👇️️ Sat Sep 24 2022 07:30:14 console.log[date]; // 👇️ "2022-09-24T04:30:14.000Z" [ISO 8601] console.log[date.toISOString[]];
The toISOString method returns a string of the date in the ISO 8601 format according to universal time.
The ISO string can easily be passed to the Date[]
constructor to create a new Date
object.