简体   繁体   中英

How to convert ISOString to date format dd/mm/yyyy using javascript

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?

 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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM