Home > Software engineering >  Display current date in a specific format in c#
Display current date in a specific format in c#

Time:09-29

I am trying to display the current date in a specific format.

For example, "Package will be delivered this ___ day of ____________, _____ at the company shop." The output would be "Package will be delivered this (29) day of (September), (2022) at the company shop.". Any help is much appreciated thank you.

CodePudding user response:

DateTime has everything you need:

DateTime now = DateTime.Now;
string s = $"Package will be delivered this {now.Day} day of {now:MMMM}, {now.Year} at the company shop.";

For the full month name i'm using the MMMM format specifier.

You can use custom format specifier for all, if you prefer:

string s = $"Package will be delivered this {now:dd} day of {now:MMMM}, {now:yyyy} at the company shop.";

CodePudding user response:

With this, from here,

string GetDaySuffix(int day) =>
day switch
{
    1 or 21 or 31 => "st",
    2 or 22 => "nd",
    3 or 23 => "rd",
    _ => "th",
};

You can do,

var now = DateTime.Now;
var legalDate = $"this {now:d}{GetDaySuffix(now.Day)} day of {now:MMMM}, {now:yyyy}";

Note,

The date suffix code is culture insensitive but since your text appears to be English in a British style I've assumed would both, like to suffix the day of the month and wouldn't need the suffix in a different language (if other cultures even do that?)

CodePudding user response:

Mine Solution is to use extension method, it will save some time in writing a wrapper method and passing date and time as input.

Result:

Package will be delivered this 29 day of 09, 2022 at the company shop.

As the execution will be as:

global using ExtensionMethods;

Console.WriteLine(DateTime.Today.ToString("dd/MM/yyyy").ToCustomDateFormat());

And the Extension Method will be:

namespace ExtensionMethods
{
    public static class MyExtensions
    {
        public static string ToCustomDateFormat(this string str)
        {
            string day = str.Substring(0, str.IndexOf('/'));
            string month = str.Substring(str.IndexOf('/')   1, str.IndexOf('/', str.IndexOf('/')));
            string year = str.Substring(str.LastIndexOf('/')   1, str.Length - str.LastIndexOf('/') - 1);

            string result = $"Package will be delivered this {day} day of {month}, {year} at the company shop.";

            return result;
        }
    }
}

Is my code and knowledge is ok compare to my 2.5 year experience of c#. Please don't find it rude I'm 15. And can anyone suggest me, how much will be my hourly-wage. And what things are required me to learn to enter in entry level? will be Very Thank-ful.

  • Related