Format date string in a specific pattern

I have a to display Date format in this format

Tuesday April 17 6:12:02 2018

I have tried this

class Program
{
    static void Main(string[] args)
    {
        var today = DateTime.Now.AddDays(-1);
        var day = today.Day;
        var month = today.Month;
        var year = today.Year;

        Console.WriteLine(today);
        Console.WriteLine(day);
        Console.WriteLine(month);
        Console.WriteLine(year);
        var answer = day + "/" + month + "/" + year;
        Console.WriteLine(answer);
        Console.WriteLine(today);
    }
}

How can I get the Month and Day like Tuesday, Wednesday in full text , also can the date be changed to AM and PM... I can get the year and date in int.


This was taken from the docs listed in the comments. You basically add in the string format patterns with the format you want to display. Notice there is a difference between uppercase and lowercase formats.

As Mentioned by Soner Gönül, if you are targeting an audience to not be english based then consider adding in a CultureInfo.InvariantCulture field to the toString() . That way the date displayed is not tied to a certain culture. Just don't forget to include System.Globalization .

From the docs:

Invariant culture data is stable over time and across installed cultures and cannot be customized by users. This makes the invariant culture particularly useful for operations that require culture-independent results, such as formatting and parsing operations that persist formatted data

var today = DateTime.Now.AddDays(-1);

Console.WriteLine(today.ToString("dddd MMMM dd hh:mm:ss tt yyyy", CultureInfo.InvariantCulture));

// Monday April 16 12:11:06 PM 2018 <- My time

This is a classic formatting question.

If you wanna get textual (aka string) representation of a DateTime , the most usual way is using ToString method with optional format and culture settings.

Your aimed string contains english-based month and day names. That's why you need to use an english-based culture setting like InvariantCulture .

And putting formats in your string, you just need to follow the rules on custom date and time format strings page.

var answer = DateTime.Now.AddDays(-1).ToString("dddd MMMM dd h:mm:ss yyyy", 
                                               CultureInfo.InvariantCulture);
链接地址: http://www.djcxy.com/p/75120.html

上一篇: DateTime.TryParseExact不会分析看起来有效的日期字符串

下一篇: 以特定模式格式化日期字符串