Ulhas Tuscano
Ulhas Tuscano

Reputation: 5620

How to convert date time in standard format

I get date in proper format from the database but i get time in improper format i.e 19/10/2010 4:45:00 AM . I want my time to be hh:mm:ss. I am getting only single hour i.e h. Appending 0 doesnt seem to be a good solution what is an alernative to parse it in expected format i.e hh:mm:ss?

Upvotes: 1

Views: 1108

Answers (7)

amod
amod

Reputation: 4272

yourDate.ToString("dd-MM-yyyy HH:mm:ss");

USE THIS IT WILL WORK.

Upvotes: 0

Cos Callis
Cos Callis

Reputation: 5084

There is nothing "improper" about the date format you are receiving, that is simply the default format for your database (which I believe can be changed by your dba if appropriate)

You want to change the rendered format. You can do this using DateTime.ToString(string Format)

 DateTime dt = DateTime.Parse("19/10/2010 4:45:00 AM");
 dt.ToString("hh:mm:ss");

Parsing is how the DateTime object reads the existing format to set it's value, ToString is about rendering it out.

Upvotes: 0

InBetween
InBetween

Reputation: 32790

I'm not sure what your problem is. How are you getting a date with improper format from the database? Are you receiving an already formatted string?

If so, then you can parse it into a valid DateTime using the following:

DateTime d = 
    DateTime.ParseExact(date, "dd/MM/yyyy h:mm:ss tt",CultureInfo.InvariantCulture);

If you already have a DateTime then you can format it to a string with any of the methods already proposed in the other answers.

Upvotes: 0

Deepesh
Deepesh

Reputation: 5614

If you are using Sql Server then use

Convert(getdate(),varchar(15),109)

Details can be found here SQL Server Date Time Format

Upvotes: 0

VMAtm
VMAtm

Reputation: 28366

Use dateTime.ToString("g");//g - general datetime format.
Custom Date and Time Format Strings

or use some custom format: dateTime.ToString("dd/MM/yyyy HH:mm:ss");
Standard Date and Time Format Strings

Upvotes: 5

Akram Shahda
Akram Shahda

Reputation: 14781

Pass the right format to the DateTime.ToString Method as the following:

dateValue.ToString("dd/MM/yyyy hh:mm:ss tt");

Upvotes: 2

Jakob Gade
Jakob Gade

Reputation: 12427

Did you try:

yourDate.ToString("dd-MM-yyyy HH:mm:ss");

The uppercase "HH" indicates the 24-hour formatting...

Upvotes: 6

Related Questions