-4

I have the a string that is loaded dynamically. The string contains information that is the date that a post is published. Unfortunately it's in a format that is not suitable for the content its added to. I would like to be able to dynamically edit the string so that only the date is showing and it appears in a day/month/year format. The following is an example of a string:

<div>2016-01-14T10:30:37+02:00</div>

How can I format the string so that it always looks like the following:

<div>14/01/2016</div>
  • Easy.... `$('div').text('14/01/2016');` Sure, it's not perfect, but it's better than *your* attempt – musefan Apr 12 '17 at 14:48
  • Possible duplicate of [jQuery date formatting](http://stackoverflow.com/questions/5250244/jquery-date-formatting) – indubitablee Apr 12 '17 at 14:49
  • i presume he wants to extract the date for each day, month and year and then change it I would suggest maybe some regex.(even though i hate it) Place the year in one var, Month in another and day in another and then change to contents like musefan suggested – bpb101 Apr 12 '17 at 14:50
  • You'll need to post the javascript code that produces what you have. – Jon B Apr 12 '17 at 14:52
  • With [**moment.js**](http://momentjs.com/) library you pass that string as argument and it will return the date on the format you want. – Marcos Pérez Gude Apr 12 '17 at 14:53

1 Answers1

0

You can follow this code:

HTML

<div class="date-string">2016-01-14T10:30:37+02:00</div>
<div class="date-string">2013-02-16T10:30:37+02:00</div>
<div class="date-string">2017-03-15T10:30:37+02:00</div>

JavaScript

var d, newDateFormat;

function getZero(number){
 if(number < 10) return '0' + number;
 return number;
}

$('.date-string').each(function(){
 d = new Date($(this).html());

 newDateFormat = getZero(d.getDate()) + '/' + getZero(d.getMonth() + 1) + '/' + d.getFullYear();

 $(this).html(newDateFormat);
});

And here is the output:

enter image description here

Jitu Raiyan
  • 498
  • 6
  • 13