4

I've an input text box with a date-picker, when the user selects a particular date, the date say 09-Dec-2014 gets applied to the input text box. On submit, I want the date to be passed to the server in yyyymmdd format say 20141209. So how to convert the date format in javascript?

var date = new Date(Date.parse('09-Dec-2014'));

Above code gives me 'Invalid date'.

Searched the net for solution but was not able to find for my problem.

Can someone help me out?

Thanks.

kumareloaded
  • 3,882
  • 14
  • 41
  • 58
  • 1
    If you're looking to use a date object first, you can find your answer by looking at [How can I convert string to datetime with format specification in JavaScript?](http://stackoverflow.com/q/476105/2074608) and [Where can I find documentation on formatting a date in JavaScript](http://stackoverflow.com/q/1056728/2074608). If on the other hand, you're just looking to convert the string directly from one form to another, there's a much simpler way of doing this. – Qantas 94 Heavy Dec 09 '14 at 12:56

4 Answers4

4

Thanks for the answers Danyal Sandeelo and Jeeva Jsb.

I was able to get the date in yyyymmdd format using the code given below.

var date = '09-Dec-2014'.split("-");
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun','Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
for(var j=0;j<months.length;j++){
    if(date[1]==months[j]){
         date[1]=months.indexOf(months[j])+1;
     }                      
} 
if(date[1]<10){
    date[1]='0'+date[1];
}                        
var formattedDate = date[2]+date[1]+date[0];
kumareloaded
  • 3,882
  • 14
  • 41
  • 58
2
 var date = '09-Dec-2014'.split("-");
 var newDate=date[2]+date[1]+date[0];

Something really quick may be, split and generate your own.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
1

The problem lies in the format that you pass the required date to the Date() object.

For some reason browsers surprisingly do not support the date format “yyyy-mm-dd” and therefore fail.

The following formats are definitely supported across all browsers and would advise sticking to one of these to avoid errors:

var d = new Date(2011, 01, 07); // yyyy, mm-1, dd  
var d = new Date(2011, 01, 07, 11, 05, 00); // yyyy, mm-1, dd, hh, mm, ss  
var d = new Date("02/07/2011"); // "mm/dd/yyyy"  
var d = new Date("02/07/2011 11:05:00"); // "mm/dd/yyyy hh:mm:ss"  
var d = new Date(1297076700000); // milliseconds  
var d = new Date("Mon Feb 07 2011 11:05:00 GMT"); // ""Day Mon dd yyyy hh:mm:ss GMT/UTC  

alert(d.getFullYear()+""+(d.getMonth()+1)+""+((d.getDate()<10)?"0"+d.getDate():d.getDate()));

Reference :

http://biostall.com/javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari

Jeeva J
  • 3,173
  • 10
  • 38
  • 85
0

The given answers only work with dates which exactly match the format whereas I needed a solution which would work for user input which sometimes do not follow that format so I created a function that works for case insensitive month and months like January or space or hyphen or slash separators. Also if no days or months are given it returns just the date. The function returns 2004-12-30 for 30 December 2004 and 1893 for Jan 1893. The input string should be trimmed as the first and last char need to be digits.

const dateStr = str => {
    const months = {'jan': "01", 'feb': "02", 'mar': "03", 'apr': "04", 'may': "05", 'jun': "06", 'jul': "07",
                'aug': "08", 'sep': "09", 'oct': "10", 'nov': "11", 'dec': "12"};
    let year = str.match(/\d{4}$/);
    let month = str.match(/[A-Za-z]{3}/);
    let day = str.match(/^[1-9][0-9]?/);
    let mm, dd;
    if(day && month && year) {
        mm = months[month[0].toLocaleLowerCase()];
        dd = day[0].padStart(2, '0');
        console.log("Input: " + str + ".  date: " + year[0] + "-" + mm + "-" + dd);
    } else if(year){
        console.log("Input: " + str + ".  date: " + year[0]);
    }
    else {
        return false;
    }
}