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?
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?
Share Improve this question edited Jul 24, 2016 at 7:35 Mohammad 21.5k16 gold badges57 silver badges85 bronze badges asked Jul 24, 2016 at 6:06 Dyana PutryDyana Putry 1071 silver badge8 bronze badges 1- let me konw if answer is usefyul @Dyana Putry – Abdennour TOUMI Commented Jul 24, 2016 at 6:12
3 Answers
Reset to default 2You 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="postupdate">2015-03-01T14:28:28Z</span>
var d = $(".postupdate").html();
var date=new Date(d);
Then using X-Class package:
date.format('dd/mm/yyyy');
// 01/03/2015
DEMO
Option:1
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>')
Option 1 JSFIDDLE
Option:2
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>')
Option 2 JSFIDDLE