Saturday, February 27, 2021

Convert a string to a date with javascript method

Change string to date is a frequent action.

Below you can find javascript method which return Date from string.

Function name is stringToDate.

Input parameters are:

  • _date parameter with date in string format
  • _format parameter - use yyyy, dd and MM. Example : yyyy.MM.dd
  • _delimiter - delimiter, for example ".". Can be omitted

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<script>

console.log(stringToDate("01/9/2020","dd/MM/yyyy","/")); // Tue Sep 01 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("9 2020","MM yyyy"," ")); // Tue Sep 01 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("9/17/2020","mm/dd/yyyy","/")); // Thu Sep 17 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("9-17-2020","mm-dd-yyyy","-")); // Thu Sep 17 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("09/2/2020","mm/dd/yyyy","/")); // Wed Sep 02 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("01/9/2020","dd/MM/yyyy")); // Tue Sep 01 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("9 2020","MM yyyy")); // Tue Sep 01 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("9/17/2020","mm/dd/yyyy")); // Thu Sep 17 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("9-17-2020","mm-dd-yyyy")); // Thu Sep 17 2020 00:00:00 GMT+0200 (Central European Summer Time)
console.log(stringToDate("09/2/2020","mm/dd/yyyy")); // Wed Sep 02 2020 00:00:00 GMT+0200 (Central European Summer Time

function stringToDate(_date,_format,_delimiter)
{
            if (!_delimiter)
                _delimiter = _format.match(/\W/g)[0];

            var formatLowerCase=_format.toLowerCase();
            var formatItems=formatLowerCase.split(_delimiter);
            var dateItems=_date.split(_delimiter);
            var monthIndex=formatItems.indexOf("mm");
            var dayIndex=formatItems.indexOf("dd");
            var yearIndex=formatItems.indexOf("yyyy");
            var month=parseInt(dateItems[monthIndex]);
            month-=1;

            var day = 1;
            if (dayIndex >= 0)
                day = dateItems[dayIndex];

            var formatedDate = new Date(dateItems[yearIndex], month, day);
            return formatedDate;
}

</script>

No comments: