remove zero before single digit in DateTime

Socks93

Active member
Joined
Oct 22, 2021
Messages
29
Programming Experience
Beginner
Hi there,

i am currently working on .Net application which is using Optimizely to render the website. At the moment the date picker that is being used returns a 0 when selecting a day which has a single digit:

1678998580844.png


The code which formats the date can be found below:

C#:
 public static string FormatDay(this DateTime date)
        {
            string suffix = date.Day switch
            {
                1 or 21 or 31 => "st",
                2 or 22 => "nd",
                3 or 23 => "rd",
                _ => "th",
            };
            return date.ToString("dd\"" + suffix + "\" MMM");
        }

I have tried returning the string as ("d\"" + suffix + "\" MMM") but this never worked. Does anyone here have any sugestions on how i can make this work?

Thanks
 
@Aaron.soggi92 : Can you be more descriptive about "never worked"? What errors are you getting? If you aren't getting an error what output are you getting?

@alexhortdog95 He is doing a custom date time string. The customization he is using is d"{suffix}" MMM.

Putting the suffix in quotes is supposed to tell the formatter to treat the characters in quotes as literal:
 
The following seems to work correctly:
C#:
using System;
                    
public class Program
{
    public static void Main()
    {
        var baseDate = new DateTime(1970, 1, 1);
        for(int i = 0; i < 31; i++)
        {
            var date = baseDate.AddDays(i);
            string suffix = date.Day switch
            {
                1 or 21 or 31 => "st",
                2 or 22 => "nd",
                3 or 23 => "rd",
                _ => "th",
            };
            Console.WriteLine(date.ToString($"d\"{suffix}\" MMMM"));
        }
    }
}

Code:
1st January
2nd January
3rd January
4th January
5th January
6th January
7th January
8th January
9th January
10th January
11th January
12th January
13th January
14th January
15th January
16th January
17th January
18th January
19th January
20th January
21st January
22nd January
23rd January
24th January
25th January
26th January
27th January
28th January
29th January
30th January
31st January

.NET Fiddle: C# Online Compiler | .NET Fiddle
 
But you do need the quotes (which can be apostrophes by the way, bit neater) otherwise look what happens:


The 1st of the month gets a format string of "dst MMMM" which is interpreted as "day seconds meridian month"

Same for nd and rd (the d is day) and th (meridian hour)
 
Back
Top Bottom