Keston Pollard Keston Pollard - 20 days ago 6
Javascript Question

Replace string (3-11-2012) with other date format (3 november 2012)

I have text strings like '11-1-2012' and I'd like that to convert into date strings like '11 januari 2012'. How do I do this? I searched but could not find exactly what I need. The dates (month names) need to be in Dutch. I tried using datepicker doing something like

$(".txtToDate").datepicker.parseDate( "d MM yy", "1 november 2001" );


but that doesn't work. JavaScript or jQuery is what I prefer...

thanks!!

Answer

There are so many ways to solve this.

Here's the final solution working on for each month. Hope it helps :)

var elements = document.getElementsByClassName("txtToDate");
for (var i = 0; i < elements.length; i++) {
  var userMonth = elements[i].innerHTML;
  var updatedText =  myFunction(userMonth);
  elements[i].innerHTML = updatedText;
}

function myFunction(str){

var currentMonth = '';

var months = ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"];

var arr = str.split("-");
var x = arr[1];
    if(x.startsWith("0")){
        currentMonth = x.slice(1);
    }
    else if(!x.startsWith("0")){
       currentMonth = x; 
    }

switch(currentMonth){
    case "1": currentMonth = months[currentMonth - 1]; break;
    case "2": currentMonth = months[currentMonth - 1]; break;
    case "3": currentMonth = months[currentMonth - 1]; break;
    case "4": currentMonth = months[currentMonth - 1]; break;
    case "5": currentMonth = months[currentMonth - 1]; break;
    case "6": currentMonth = months[currentMonth - 1]; break;
    case "7": currentMonth = months[currentMonth - 1]; break;
    case "8": currentMonth = months[currentMonth - 1]; break;
    case "9": currentMonth = months[currentMonth - 1]; break;
    case "10": currentMonth = months[currentMonth - 1]; break;
    case "11": currentMonth = months[currentMonth - 1]; break;
    case "12": currentMonth = months[currentMonth - 1]; break;
}
var text = arr[0] + " " + currentMonth + " " + arr[2];

return text;
}
<div class = "txtToDate">11-01-2012</div>
<div class = "txtToDate">11-02-2012</div>
<div class = "txtToDate">11-03-2012</div>
<div class = "txtToDate">11-04-2012</div>
<div class = "txtToDate">11-05-2012</div>
<div class = "txtToDate">11-06-2012</div>
<div class = "txtToDate">11-07-2012</div>
<div class = "txtToDate">11-08-2012</div>
<div class = "txtToDate">11-09-2012</div>
<div class = "txtToDate">11-10-2012</div>
<div class = "txtToDate">11-11-2012</div>
<div class = "txtToDate">11-12-2012</div>