Reputation: 75
Can someone help me convert the string 14/04/2010 10:14:49.PM to datetime in C#.net without losing the time format?
Upvotes: 5
Views: 2498
Reputation: 53685
var date = DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss.tt", null);
For string representation use
date.ToString(@"dd/MM/yyyy hh:mm:ss.tt");
Also you can create extention method like this:
public enum MyDateFormats
{
FirstFormat,
SecondFormat
}
public static string GetFormattedDate(this DateTime date, MyDateFormats format)
{
string result = String.Empty;
switch(format)
{
case MyDateFormats.FirstFormat:
result = date.ToString("dd/MM/yyyy hh:mm:ss.tt");
break;
case MyDateFormats.SecondFormat:
result = date.ToString("dd/MM/yyyy");
break;
}
return result;
}
Upvotes: 5
Reputation: 473
DateTime result =DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy HH:mm:ss.tt",null);
You can now see the PM or AM and null value for format provider
Upvotes: 3
Reputation: 19928
I recommend using DateTime.ParseExact
as the Parse
method behaves slightly differently according to the current thread locale settings.
DateTime.ParseExact(yourString,
"dd/MM/yyyy hh:mm:ss.tt", null)
Upvotes: 0
Reputation: 2601
Use convert function
using System;
using System.IO;
namespace stackOverflow
{
class MainClass
{
public static void Main (string[] args)
{
Console.WriteLine(Convert.ToDateTime("14/04/2010 10:14:49.PM"));
Console.Read();
}
}
}
Upvotes: 0
Reputation: 1770
DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss");
Upvotes: 1
Reputation: 17213
DateTime.Parse(@"14/04/2010 10:14:49.PM");
that should work, not near VS at the moment so i cannot try it
Upvotes: 0