5

Can someone help me convert the string 14/04/2010 10:14:49.PM to datetime in C#.net without losing the time format?

1
  • 1
    What do you mean by without losing the time format? Commented Dec 5, 2010 at 20:14

6 Answers 6

5
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;
    }
Sign up to request clarification or add additional context in comments.

3 Comments

The string representation should use hh instead of HH. During parsing the difference is not that big but for output you would get 23h instead of 11h (PM)
The extension method also needs to be static.
ohh, yes. It just because i haven't vs near me. Updated.
3
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

Comments

1
DateTime.ParseExact(@"14/04/2010 10:14:49.PM", @"dd/MM/yyyy hh:mm:ss");

Comments

0
DateTime.Parse(@"14/04/2010 10:14:49.PM");

that should work, not near VS at the moment so i cannot try it

3 Comments

this has an ambiguous date/month format, so that won't work in some scenarios
I agree with Myster. The behaviour is locale dependent.
Assuming this is the correct format of DateTimeFormatInfo.CurrentInfo , this should work.
0

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();

        }
    }
}

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.