Skip to content Skip to sidebar Skip to footer

Reworking A Date String From Yyyy-mm-dd To Dd/mm/yyyy

I need your help, how can I rework and restring a date string from yyyy-mm-ddd to dd/mm/yyyy? Example: 2014-06-27, firstly replace the dash with a slash, then shift the order of th

Solution 1:

I've made a custom date string format function, you can use that.

var  getDateString = function(date, format) {
        var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        getPaddedComp = function(comp) {
            return ((parseInt(comp) < 10) ? ('0' + comp) : comp)
        },
        formattedDate = format,
        o = {
            "y+": date.getFullYear(), // year
            "M+": months[date.getMonth()], //month
            "d+": getPaddedComp(date.getDate()), //day
            "h+": getPaddedComp((date.getHours() > 12) ? date.getHours() % 12 : date.getHours()), //hour
             "H+": getPaddedComp(date.getHours()), //hour
            "m+": getPaddedComp(date.getMinutes()), //minute
            "s+": getPaddedComp(date.getSeconds()), //second
            "S+": getPaddedComp(date.getMilliseconds()), //millisecond,
            "t+": (date.getHours() >= 12) ? 'PM' : 'AM'
        };

        for (var k in o) {
            if (new RegExp("(" + k + ")").test(format)) {
                formattedDate = formattedDate.replace(RegExp.$1, o[k]);
            }
        }
        return formattedDate;
    };

And now suppose you've :-

var date = "2014-06-27";

So to format this date you write:-

var formattedDate = getDateString(new Date(date), "d/M/y")

Solution 2:

if you're using a string, then the string.split would be an easy way to do this.

C# code:

public void testDateTime() {

string dashedDate = "2014-01-18"; // yyyy-mm-dd
var stringArray = dashedDate.Split('-');
string newDate = stringArray[2] + "/" + stringArray[1] + "/" + stringArray[0];
//convert to dd/mm/yyyy
Assert.AreEqual(newDate, "18/01/2014");

}


Post a Comment for "Reworking A Date String From Yyyy-mm-dd To Dd/mm/yyyy"