Euphe
Euphe

Reputation: 3709

How to parse a date string to dd/mm/yyyy?

I have this string:

3913-12-10T20:00:00+0000

How do I change it to dd/mm/yyyy format? My main problem is that I don't recognzie the pattern. It's actually 11/11/2013, but I don't get how to extract it.

Upvotes: 0

Views: 145

Answers (3)

Cracker0dks
Cracker0dks

Reputation: 2490

Do it just like this:

var d= new Date("3913-12-10T20:00:00+0000");
var newDate =  d.getDate() + '/' + d.getMonth() + '/' + d.getFullYear();

or any other date format function you know.

Upvotes: 3

gen_Eric
gen_Eric

Reputation: 227310

The server you are getting this data from is giving you bad data. You should report this to them so they can fix it. They are probably using deprecated APIs and/or building this string (incorrectly) by hand.

The string is valid ISO-8601, except the year is offset by +1900, the month by +1 and the day by -1.

So, one solution is to parse it as-is and then offset the date object. I, personally, love the moment.js library for dealing with dates in JavaScript.

var dateString = '3913-12-10T20:00:00+0000',
    dateObj = moment(dateString);

dateObj.subtract({'y': 1900, 'M': 1}).add('d', 1);

console.log(dateObj.format('MM/DD/YYYY')); // 11/11/2013

Or if you prefer using native Date objects:

var dateString = '3913-12-10T20:00:00+0000',
    dateObj = new Date(dateString);

dateObj.setFullYear(dateObj.getFullYear() - 1900);
dateObj.setMonth(dateObj.getMonth() - 1);
dateObj.setDate(dateObj.getDate() + 1);

console.log(dateObj.toDateString()); // Mon Nov 11 2013

Upvotes: 2

user3355603
user3355603

Reputation: 1171

    function dateString(d, i) {

        var m_names = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

        var curr_date = d.getDate() + i;
        var sup = "";

        if (curr_date == 1 || curr_date == 21 || curr_date ==31){
           sup = "st";
        }
        else if (curr_date == 2 || curr_date == 22){
           sup = "nd";
        }
        else if (curr_date == 3 || curr_date == 23){
           sup = "rd";
        }
        else{
           sup = "th";
        }

        var curr_month = d.getMonth();
        var curr_year = d.getFullYear();

        var dateString = curr_date + sup + " " + m_names[curr_month] + " " + curr_year;

        return dateString;

    }

Upvotes: -2

Related Questions