Lajja Thaker
Lajja Thaker

Reputation: 2041

SQL convert dd-MM-yyyy HH:mm:SS to MM/dd/yyyy

How can I convert '11-09-2012 5:08:31 PM' to '09/11/2012'? (From dd-MM-yyyy HH:mm:SS to MM/dd/yyyy).

Date is 11 September 2012.
Or is there any way to convert this in C#? But in C# I want only date not string.

Upvotes: 3

Views: 18374

Answers (5)

Himanshu
Himanshu

Reputation: 32602

Using SQL Server query:

SELECT CONVERT(DATETIME, '11-09-2012 5:08:31 PM', 101);

This will convert in MM/dd/yyyy.For more info see CAST and CONVERT (Transact-SQL) and How to convert from string to datetime?


To convert using C#.

You can do that like this:

string myDate = Convert.ToDateTime("11-09-2012 5:08:31 PM").ToString("MM/dd/yyyy"
                                                  ,CultureInfo.InvariantCulture);

But as you don't want result in String, you can use DateTime.ParseExact method.

DateTime parsedDate = DateTime.ParseExact("11-09-2012 5:08:31 PM", 
                                          "MM/dd/yyyy", 
                                          CultureInfo.InvariantCulture);

Upvotes: 5

Akash KC
Akash KC

Reputation: 16310

SQL SERVER :

Do like this for [MM/DD/YYYY] format:

SELECT CONVERT(VARCHAR(10), CAST('11-09-2012 5:08:31 PM' AS DATETIME), 101) AS [MM/DD/YYYY]

Similary, if you want to convert in [DD/MM/YYYY] format, you can do like this

SELECT CONVERT(VARCHAR(10), CAST('11-09-2012 5:08:31 PM' AS DATETIME), 103) AS [DD/MM/YYYY]

C#

In C#, you simply do like this:

string formattedDt= Convert.ToDateTime("11-09-2012 5:08:31 PM")
                           .ToString("MM/dd/yyyy",CultureInfo.InvariantCulture);

Upvotes: 1

Aravind.HU
Aravind.HU

Reputation: 9472

Here is the sample code using Date time parse and for more information you can visit the link C-sharp date time formats

string inputString = "11/08/2012";
DateTime dt = DateTime.MinValue;
try {
dt = DateTime.Parse(inputString);    
} 
catch (Exception ex) {
// handle the exception however you like.
return;
}
string formattedDate = String.Format("{0:MMM d, yyyy}", dt);

Upvotes: 0

andy
andy

Reputation: 6079

string date = "11-09-2012 5:08:31 PM";
string newDate = DateTime.Parse(date).ToString("dd/MM/yyyy");

Upvotes: 0

Taryn
Taryn

Reputation: 247720

In c# you should be able to use the method:

DateTime.ToShortDateString();

Or even:

DateTime.Now.Date -- will produce just the date

Note from MSDN:

The string returned by the ToShortDateString method is culture-sensitive. It reflects the pattern defined by the current culture's DateTimeFormatInfo object. For example, for the en-US culture, the standard short date pattern is "M/d/yyyy"; for the de-DE culture, it is "dd.MM.yyyy"; for the ja-JP culture, it is "yyyy/M/d". The specific format string on a particular computer can also be customized so that it differs from the standard short date format string.

Upvotes: 0

Related Questions