Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove leading zero form month C#

Tags:

c#

datetime

I'm having trouble to remove the leading zero from a date I found this on the miscrosoft website.

DateTime date1 = new DateTime(2008, 8, 18);
Console.WriteLine(date1.ToString("(M) MMM, MMMM", 
                  CultureInfo.CreateSpecificCulture("en-US")));
// Displays (8) Aug, August

Totally doesn't work here.

This is my code:

string date = '2013-04-01'
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.ToString("M");

Test is now 01 April

I just need it to be 4 in a string or int idc Thanks!

Edit if I do:

billrunDate.ToString("(M)");

I get (4), but I dont need ()

EDIT 2: Well this works

string test = billrunDate.ToString(" M ");
string testTwo = test.Trim();

Very very ugly

like image 853
Freddy Avatar asked Apr 12 '13 14:04

Freddy


3 Answers

One of my most referenced MSDN pages is the Custom Date & Time Format Strings page. You can use these as part of the formatting passed in to the ToString() method. If any of them are standard formatting patterns (as "M" is) and you want to use them along, you have to preface them with '%' or have a space before or after them in the format string (so use "%M", " M", or "M " instead of "M").

Relevant section:

"M"

The month, from 1 through 12.

"MM"

The month, from 01 through 12.

"MMM"

The abbreviated name of the month.

"MMMM"

The full name of the month.

like image 44
Jeff Avatar answered Sep 27 '22 22:09

Jeff


It's interpreting M as a standard date and time format for "month day pattern".

To interpret a single character pattern as a custom date and time pattern, just prefix it with %:

string test = billrunDate.ToString("%M");
like image 163
Jon Skeet Avatar answered Sep 27 '22 22:09

Jon Skeet


You don't need to convert to string the date to retrieve the month number.
Just read the Month property of the DateTime class:

string date = "2013-04-01";
DateTime billrunDate = Convert.ToDateTime(date);
string test = billrunDate.Month.ToString();
like image 33
Cyril Gandon Avatar answered Sep 27 '22 22:09

Cyril Gandon