最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to convert date format from dd-MMM-yyyy to yyyymmdd in Javascript? - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Dec 9, 2014 at 12:42 kumareloadedkumareloaded 3,95214 gold badges42 silver badges60 bronze badges 1
  • 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? and Where can I find documentation on formatting a date in JavaScript. 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 Commented Dec 9, 2014 at 12:56
Add a ment  | 

5 Answers 5

Reset to default 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];
 var date = '09-Dec-2014'.split("-");
 var newDate=date[2]+date[1]+date[0];

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

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./javascript-new-date-returning-nan-in-ie-or-invalid-date-in-safari

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;
    }
}

Taking Dennis Nolan's answer and Easiest way to convert month name to month number in JS ? (Jan = 01) to deal with monthStr to MonthNumber conversation

function changeDateStringFormat(dd_mmm_yyy){
  
  //get the year, month and day in spearate objects
  let year = dd_mmm_yyy.match(/\d{4}$/)[0];
  let month = dd_mmm_yyy.match(/[A-Za-z]{3}/)[0];
  let day = dd_mmm_yyy.match(/^\d{2}?/)[0];

  //if day and month and year were captured
  if(day && month && year) {
    
    //get the mm and dd padded if needed
    let mm, dd;
    mm = (new Date(Date.parse(month +" 1, 2012")).getMonth()+1).toString().padStart(2,'0');
    dd = day.padStart(2, '0');

    //and return date in the string format needed
    return year + '-' + mm + '-' + dd // return yyyy-mm-dd

  }else{
    return false;
  }
}
发布评论

评论列表(0)

  1. 暂无评论