Nitin Arote
Nitin Arote

Reputation: 71

C#, DateTime conversion

Need help to convert datetime object into specific format. It may be duplicate question but i gone through many articles and question and answers provided in Stackoverflow but didn't get answer. Current my date format is {dd/mm/yyyy 8:12:56 AM} which is default date time format. I want to convert in {mm/dd/yyyy 8:12:56 AM} format.

DateTime searchDateTime = Datetime.Now.AddYears(-1));

string test = searchDateTime.ToString("dd-MMM-yyyy");

Its giving me format which i have given in ToString.

DateTime date = Convert.ToDateTime(test);

But when i am trying to convert string to datetime format, its returning dd/mm/yyyy formatted date.

Upvotes: 0

Views: 262

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186833

Try using DateTime.ParseExact if you want parse the string with known format and ToString when you want to represent DateTime into the desired format:

using System.Globalization;

...

DateTime searchDateTime = new DateTime(2019, 2, 25, 16, 15, 45);

// Escape delimiters with apostrophes '..' if you want to preserve them
string test = searchDateTime.ToString(
  "dd'-'MMM'-'yyyy' 'h':'mm':'ss' 'tt", 
   CultureInfo.InvariantCulture);

// Parse string with known format into DateTime 
DateTime date = DateTime.ParseExact(
   test, 
  "dd'-'MMM'-'yyyy' 'h':'mm':'ss' 'tt", 
   CultureInfo.InvariantCulture); 

// Presenting DateTime as a String with the desired format 
string result = date.ToString(
  "MM'/'dd'/'yyyy' 'h':'mm':'ss' 'tt", 
   CultureInfo.InvariantCulture);

Console.WriteLine($"Initial: {test}");
Console.Write($"Final:   {result}");

Outcome:

Initial: 25-Feb-2019 4:15:45 PM
Final:   02/25/2019 4:15:45 PM

Upvotes: 2

Related Questions