DateTimeOffset format and get the same output as moment.js

Viewed 451

I am able to format date in moment.js with this pattern:

MMMM Do YYYY, h:mm:ss a

And it will return:

January 1st 0001, 12:00:24 am

However, doing the same with C# DateTimeOffset will return:

date.ToString("MMMM Do YYYY, h:mm:ss a")

> January Do YYYY, 12:00:00 a

I am wondering how do I achieve the same output?

3 Answers

You can install the Humanizer nuget package and do:

date.ToString($"MMMM \"{date.Day.Ordinalize()}\" yyyy, h:mm:ss tt")

This is without Humanizer, You can create the same function for DateTimeOffset, it will work the same

    public static string ToDisplayDate(DateTime date)
    {
        int day = date.Day;
        string dayStringOrdinal = day +
            ((day % 10 == 1 && day != 11) ? "st"
            : (day % 10 == 2 && day != 12) ? "nd"
            : (day % 10 == 3 && day != 13) ? "rd" : "th");

        return date.ToString("MMMM DAY, h:mm:ss tt").Replace("DAY", dayStringOrdinal);
    }

output :

August 13th, 08:35:58 AM
   date.ToString("MMMM dd")+  GetSuffix(date.Day) + date.ToString(" yyyy, h:mm:ss a")

            string GetSuffix(int day){

            return (day % 10 == 1 && day != 11) ? "st"
            : (day % 10 == 2 && day != 12) ? "nd"
            : (day % 10 == 3 && day != 13) ? "rd"
            : "th";
             }
Related