Parsing DateTime Strings in JavaScript
In JavaScript, parsing a date string into a DateTime object can be a challenge, especially when the format doesn't match the standard dd-MM-yyyy or MM-dd-yyyy patterns. For instance, consider a date string such as "03.09.1979", where the day and month are separated by a period.
To handle such situations, we need to split the string into its individual components: day, month, and year. The String.Split method can be used for this purpose.
Next, we create a Date object using the extracted components. Note that the month argument in the Date constructor expects the month index (starting from 0), which is why we subtract 1 from the month value obtained from the splitting process.
<code class="javascript">var strDate = "03.09.1979"; var dateParts = strDate.split("."); var date = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);</code>
This code snippet effectively parses the "03.09.1979" string into a Date object, allowing subsequent manipulation and formatting of the date as required.
The above is the detailed content of How to Parse Non-Standard DateTime Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!