Change Date Format Inside Html With Javascript
I have the following code on a page: 2014-11-16 This 2014-11-16 is the date and is genera
Solution 1:
Here's a snippets with jQuery and Moment.js that does what you want, I made format into a variable so you can play with is.
$('.release-date').each( function() {
var format = "Do MMM YYYY";
var $this = $( this );
var old_date = $.trim($this.text());
var new_date = moment(old_date , 'YYYY-MM-DD').format( format );
$this.text($this.text().replace(old_date, new_date));
});
<scriptsrc="http://momentjs.com/downloads/moment.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><spanclass="release-date"><iclass="fa fa-calendar"></i> 2014-11-16</span>
Solution 2:
You can use the Javascript Date
to save you some ugly regex
newDate("2014-11-16")
>> SatNov15201416:00:00GMT-0800 (PST)
newDate("2014-11-16 PST")
>> SunNov16201400:00:00GMT-0800 (PST)
Unless you add another library like momemt.js or something, you may need to add a little helper to get the month as a string. Something like:
functionmonthToString(month) {
var months = [ 'Jan', 'Feb', ... , 'Dec' ];
return months[month % months.length]
}
Then you can build the new date string like this
functionconvertDateString(dateFromCms) {
var date = new Date(dateFromCms);
returndate.getFullYear() + "-" + monthToString(date.getMonth()) + "-" + date.getDate();
}
Or something along those lines. Check out the MDN for more about how Date
works.
Solution 3:
If you want to select the textNode
of the span elements, you can iterate through their childNode
s and filter the textNode
:
[].forEach.call(document.querySelectorAll('.release-date'), function(el) {
var n = el.childNodes, inputDate;
for ( var i = n.length; i--; ) {
if ( n[i].nodeType === 3 && n[i].nodeValue.trim().length ) {
inputDate = n[i].nodeValue.trim();
n[i].nodeValue = // modify the input date
}
}
});
Solution 4:
You can do it this way:
Fiddle
var elem = document.getElementsByClassName('release-date')[0];
var text = elem.innerHTML;
var regex = /-(\d{1,2})-/mvar month = regex.exec(text);
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec']
if (month[1]) {
elem.innerHTML = text.replace(regex, "-" + months[parseInt(month[1], 10) - 1] + "-")
}
Solution 5:
This works too..
var months = {
1: 'jan',
2: 'feb',
3: 'march',
4: 'apr',
5: 'may',
6: 'june',
7: 'july',
8: 'aug',
9: 'sep',
10: 'oct',
11: 'nov',
12: 'dec'
};
var currentDate = "2014-11-16"; // your date string would go here. Note, I left the retrieval of it out. This is trivial w/ jQuery... $('.release-date').text();var redrawnCurrentDate = currentDate.replace(/(\d{2})-(\d{2})$/,function(_,$1,$2){
return months[$1] + "-" + $2;
});
$('.release-date').text(redrawnCurrentDate);
Post a Comment for "Change Date Format Inside Html With Javascript"