DateTime format/manipulation question

  • Thread starter Thread starter Andrew Wilhite
  • Start date Start date
A

Andrew Wilhite

Hello,

I am just learning C# and I have ran into a problem that I cannot seem
to resolve. I need to capture today's date, subtract a day, and then
put it into the MM-DD-YYYY format. I know how to do one or the
other, but i cannot figure out how to do both. Here is my code
snippet:

DateTime Date1 = System.DateTime.Now.AddDays(-1);
string Day = System.Convert.ToString(Date1.Day);
string Month = System.Convert.ToString(Date1.Month);
string Year = System.Convert.ToString(Date1.Year);
string Logs = "log" +Year+Month+Day+"*.xml";

I need the string logs to be yesterdays date and have leading zero on
the month.

Any help would be appreciated!
 
Andrew,

You can use a custom format string to generate the date. You want to do
this:

// Get the datetime (btw, your code to do this is right).
DateTime Date1 = System.DateTime.Now.AddDays(-1);

// Store the log string.
string Logs = string.Format("log{0:yyyyMMdd}*.xml", Date1);

Notice that you can place the formatting string along with the
placeholder.

Hope this helps.
 
Andrew Wilhite said:
I am just learning C# and I have ran into a problem that I cannot seem
to resolve. I need to capture today's date, subtract a day, and then
put it into the MM-DD-YYYY format. I know how to do one or the
other, but i cannot figure out how to do both. Here is my code
snippet:

DateTime Date1 = System.DateTime.Now.AddDays(-1);
string Day = System.Convert.ToString(Date1.Day);
string Month = System.Convert.ToString(Date1.Month);
string Year = System.Convert.ToString(Date1.Year);
string Logs = "log" +Year+Month+Day+"*.xml";

I need the string logs to be yesterdays date and have leading zero on
the month.

string logs = string.Format ("log{0:ddMMyyyy}",
DateTime.Now.AddDays(-1));
 
Hi,

string s = DateTime.Today.AddDays( -1).ToString( "MM-dd-yyyy");

Cheers,
 
string logs = string.Format ("log{0:ddMMyyyy}",
DateTime.Now.AddDays(-1));

Thank you! That worked perfectly and the code is a lot cleaner than before.


Thanks again!

Andrew
 
Back
Top