I want to change the date to the format dd/mm/yyyy
but I did not succeed. I tried something like this:
<span class="postupdate">2015-03-01T14:28:28Z</span>
$(function(){
var d = $(".postupdate").html();
var n = d.toLocaleDateString();
d.html(n);
});
but I do not know how to to change the date it with javascript or jquery. whether to use a regex to change that date? Can someone help me?
Use getDate
, getMonth
& getYear
method to get the date , month & year from the date. Use conditional operator to form the date format.
+1
(not unary plus) is used with getMonth
since it starts with 0,
var date=new Date('2015-03-01T14:28:28Z');
var _dd = "";
var _mm="";
var _yy = date.getFullYear();
date.getDate() <10 ? (_dd='0'+date.getDate()):(_dd=date.getDate());
(date.getMonth()+1) <10?(_mm='0'+(date.getMonth()+1)):(_mm = date.getDate()+1);
var _m = _dd + '/' +_mm+ '/' +_yy;
document.write('<pre>'+_m+'</pre>')
Using slice & split to break a split a string and create an array. Then use it's index of the array to change the format
var getDate = "2015-03-01T14:28:28Z".slice(0, 10).split('-'); //create an array
var _date =getDate[1] +'/'+ getDate[2] +'/'+ getDate[0];
document.write('<pre>'+_date+'</pre>')
You can use regex to parsing values of date. In bottom code, i used regex in .match()
to parsing day, month, year of date.
$(".postupdate").text().match(/([^T]+)/)[0].split("-").reverse().join("/");
In your case, you can use this code:
$("span").text(function(i, text){ return text.match(/([^T]+)/)[0].split("-").reverse().join("/"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="postupdate">2015-03-01T14:28:28Z</span>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.