Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToDateTime: how to set format

Tags:

I use convert like:

Convert.ToDateTime(value)

but i need convert date to format like "mm/yy".
I'm looking for something like this:

var format = "mm/yy";
Convert.ToDateTime(value, format)
like image 237
Refael Avatar asked Mar 04 '13 14:03

Refael


People also ask

What is the format of convert ToDateTime?

ToDateTime('Datestring') to required dd-MM-yyyy format of date.

How to Convert string date to MM dd yyyy format in c#?

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

How to Convert time to DateTime in c#?

You can use DateTime. TryParse() : which will convert the specified string representation of a date and time to its DateTime equivalent and returns a value that indicates whether the conversion succeeded.


2 Answers

You should probably use either DateTime.ParseExact or DateTime.TryParseExact instead. They allow you to specify specific formats. I personally prefer the Try-versions since I think they produce nicer code for the error cases.

like image 135
Fredrik Mörk Avatar answered Sep 21 '22 06:09

Fredrik Mörk


If value is a string in that format and you'd like to convert it into a DateTime object, you can use DateTime.ParseExact static method:

DateTime.ParseExact(value, format, CultureInfo.CurrentCulture);

Example:

string value = "12/12";
var myDate = DateTime.ParseExact(value, "MM/yy", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None);

Console.WriteLine(myDate.ToShortDateString());

Result:

2012-12-01
like image 20
MarcinJuraszek Avatar answered Sep 21 '22 06:09

MarcinJuraszek