Reputation: 4602
I have a string looking like so:
"2013/1/16"
Is there any way I could quickly convert it into date object in javascript, something like:
convertToDateTime("2013/1/16", "yyyy/MM/dd")
Upvotes: 5
Views: 103072
Reputation: 66
After improving the regular expression to perfectly capture against any dates, leap dates included (and discounting those invalid centennial leap years which are not wholly divisible by 400), I’ve swapped the regex to the improved version and removed the logic that was used to handle the leap day validation. Better. Stronger. Faster.
Explanation here
this function receives a string which is either in the form 'YYYY-MM-DD' or 'YYYY-MM-DDTHH:MM:SS.sssZ?'.
While this may look like a lot, don't let the number of lines fool you: the function is incredibly sparse, and most of the size comes from handling the optional parameters. Only a singular RegExp is actually used to validate the received date-string itself, and makes no use of look-aheads/behinds (negative or positive), and logical handling for leap-years is only used if the MM-DD value is equal to '02-29'.
It handles leap-years and will not validate any invalid date based on the typical rules (month > 0 && month < 13), and ensures that the day part adheres to the range for the given month.
The function also allows a few optional parameters to be passed; the time part of the resulting Date object may be set by passing in a valid time-string ('HH:MM:SS.sssZ?') for the parameter "resultTimePartStr".
The default is for the Date object to correspond to local time, but if desired it may be set to UTC by passing true for the parameter "useUTCNotLocalFlag".
It's been tested against every numeric combination for 'YYYY-MM-DD' (that's to say within the range '0000-00-00' through '9999-99-99'). No false negatives/false positives occurred.
For valid inputs, a Date object is returned.
For invalid inputs, null is returned.
That means you won't have to worry about accidentally converting a bad value into a real Date object, and can handle it accordingly.
This is not the case with converting a string to a Date via the constructor: new Date('0001-02-29') will return a Date object with a corresponding date of '0001-03-01'. Potentially useful, but this allows you to catch bad inputs immediately as opposed to attempting to chug along.
const BASIC_ISOSTR_T_DELIMITER_IDX = 10;
const ISOSTR_TIME_PART_LOCALE_STR = '00:00:00.000';
const ISOSTR_LOCAL_TERMINAL_CHAR = '';
const ISOSTR_UTC_TERMINAL_CHAR = 'Z';
const ISOSTR_TERMINAL_CHAR_ARR = [
ISOSTR_LOCAL_TERMINAL_CHAR,
ISOSTR_UTC_TERMINAL_CHAR,
];
const ISOSTR_LEAP_MONTH_DAY_STR = '02-29';
const BASIC_ISOSTR_TIME_PART_RGX = new RegExp(
/^(?:[01]\d|2[0-3])(?:[:][0-5]\d){2}[.]\d{3}Z?$/
);
// ! This regexp captures all valid dates, leap or otherwise (with an optional trailing ISO-string, for which the UTC specifier 'Z' is also optional)
const ISOSTR_DATE_TIME_LEAP_OR_NON_LEAP_RGX = new RegExp(
/^(?:(?:(?:(?:(?:[02468][048])|(?:[13579][26]))00)|(?:[0-9][0-9](?:(?:0[48])|(?:[2468][048])|(?:[13579][26]))))-02-29)|(?:\d{4}-(?:(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01]))|(?:(?:0[469]|11)-(?:0[1-9]|[12]\d|30))|(?:02-(?:0[1-9]|1[0-9]|2[0-8]))))(?:T(?:[01]\d|2[0-3])(?:[:][0-5]\d){2}[.]\d{3}Z?)?$/
);
// ! Accepts inputs of either a date-string (\d{4}-\d{2}-\d{2}) or an ISO-string (\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}[.]\d{3}Z?)
// ! Any invalid date will return null
// ! Any date-string/ISO-string with a date before 0000-01-01 or after 9999-12-31 will return null
// ! Accomodates leap-year days (any valid February 29th)
// * *A valid February-29 is a date for which the year is wholly divisible by 4;
// * if the year is also wholly divisible by 100 then it must also be wholly divisible by 400
// ! This function has been thoroughly tested against all possible inputs 0000-00-00 through 9999-99-99
function dateStringToDateObject({
dateStr,
resultTimePartStr = null,
useUTCNotLocalFlag = false,
}) {
let dateObj = null;
let timePartStr = null;
if (!!dateStr && typeof dateStr === 'string') {
switch (resultTimePartStr) {
case null: {
timePartStr = `${ISOSTR_TIME_PART_LOCALE_STR}${
ISOSTR_TERMINAL_CHAR_ARR[+(!!useUTCNotLocalFlag)]
}`;
break;
}
default: {
if (
!!resultTimePartStr &&
typeof resultTimePartStr === 'string' &&
BASIC_ISOSTR_TIME_PART_RGX.test(resultTimePartStr)
) {
resultTimePartStr.length =
resultTimePartStr.length -
(resultTimePartStr[resultTimePartStr.length - 1] ===
ISOSTR_UTC_TERMINAL_CHAR);
timePartStr = `${resultTimePartStr}${
ISOSTR_TERMINAL_CHAR_ARR[+(!!useUTCNotLocalFlag)]
}`;
}
}
}
if (!!timePartStr && ISOSTR_DATE_TIME_LEAP_OR_NON_LEAP_RGX.test(dateStr)) {
const datePartStr = dateStr.slice(0, BASIC_ISOSTR_T_DELIMITER_IDX);
dateObj = new Date(`${datePartStr}T${timePartStr}`);
}
}
return dateObj;
}
Upvotes: 0
Reputation: 1
var myDate = new Date("2013/1/16");
var str = "2013/1/16"; var strToDate = new Date(str);
Upvotes: -1
Reputation: 72967
It's pretty simple:
var myDate = new Date("2013/1/16");
That should do the trick.
Have a look at the documentation for the Date object
Upvotes: 24