[c#] Converting string format to datetime in mm/dd/yyyy

I have to convert string in mm/dd/yyyy format to datetime variable but it should remain in mm/dd/yyyy format.

string strDate = DateTime.Now.ToString("MM/dd/yyyy");

Please help.

This question is related to c# datetime

The answer is


I did like this

var datetoEnter= DateTime.ParseExact(createdDate, "dd/mm/yyyy", CultureInfo.InvariantCulture);

You need an uppercase M for the month part.

string strDate = DateTime.Now.ToString("MM/dd/yyyy");

Lowercase m is for outputting (and parsing) a minute (such as h:mm).

e.g. a full date time string might look like this:

string strDate = DateTime.Now.ToString("MM/dd/yyyy h:mm");

Notice the uppercase/lowercase mM difference.


Also if you will always deal with the same datetime format string, you can make it easier by writing them as C# extension methods.

public static class DateTimeMyFormatExtensions
{
  public static string ToMyFormatString(this DateTime dt)
  {
    return dt.ToString("MM/dd/yyyy");
  }
}

public static class StringMyDateTimeFormatExtension
{
  public static DateTime ParseMyFormatDateTime(this string s)
  {
    var culture = System.Globalization.CultureInfo.CurrentCulture;
    return DateTime.ParseExact(s, "MM/dd/yyyy", culture);
  }
}

EXAMPLE: Translating between DateTime/string

DateTime now = DateTime.Now;

string strNow = now.ToMyFormatString();
DateTime nowAgain = strNow.ParseMyFormatDateTime();

Note that there is NO way to store a custom DateTime format information to use as default as in .NET most string formatting depends on the currently set culture, i.e.

System.Globalization.CultureInfo.CurrentCulture.

The only easy way you can do is to roll a custom extension method.

Also, the other easy way would be to use a different "container" or "wrapper" class for your DateTime, i.e. some special class with explicit operator defined that automatically translates to and from DateTime/string. But that is dangerous territory.


Solution

DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)

You can change the format too by doing this

string fecha = DateTime.Now.ToString(format:"dd-MM-yyyy");

// this change the "/" for the "-"


The following works for me.

string strToday = DateTime.Today.ToString("MM/dd/yyyy");