Click here to Skip to main content
15,887,862 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I need to convert the date time format : 'Tue Aug 9 00:00:03 2016' to '2016-08-09 00:00:03'. I tried this below solution,but didn't work out. Please help me for the conversion to 'yyyy-MM-dd HH:mm:ss' format. Thanks in advance.

What I have tried:

C#
private string ParseDateTime(string dateTime)
        {
            try
            {
                DateTime dateValue; string UTC_DateTime = "";
                if (DateTime.TryParse(dateTime, out dateValue))
                {
                    UTC_DateTime = dateValue.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
                }
                else
                {
                    var date = DateTime.ParseExact(dateTime, "ddd MMM dd HH:mm:ss yyyy", CultureInfo.GetCultureInfo("en-us"));
                   UTC_DateTime = date.ToString("yyyy-MM-dd HH:mm:ss");
                }
                return UTC_DateTime;
            }
            catch (Exception ex)
            {
              return "";
            }      
        }
Posted
Updated 26-Sep-16 23:07pm
v3
Comments
Maciej Los 27-Sep-16 2:19am    
And what's wrong with your code?

First of all: a 'Tue Aug 9 00:00:03 2016' date cannot be converted into '2016-10-09 00:00:03', because due to August is 8. month in the year.

Second of all, all what you need to do is:
C#
string inputDate = "Tue Aug 9 00:00:03 2016";
string inputFormat = "ddd MMM d hh:mm:ss yyyy";
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US");

DateTime resultDate = DateTime.ParseExact(inputDate, inputFormat, provider);
//resultDate = '2016-08-09 00:00:03'


But(!), i'd suggest to use DateTime.TryParse[^] or DateTime.TryParseExact[^] method.

C#
DateTime resultDate1;

if (DateTime.TryParseExact(inputDate, inputFormat, provider, System.Globalization.DateTimeStyles.None, out resultDate1))
{
	Console.WriteLine("A result date is '{0}'", resultDate1);
}
else
{
	Console.WriteLine("String to date conversion failed!");
}


[EDIT]
Using DateTime.TryParseExact, you can loop through the set of formats, ie.:

C#
string inputDate = "Tue Aug 10 00:00:03 2016"; //'2016-10-09 00:00:03'.
string[] inputFormats = new string[] {"MMM d hh:mm:ss yyyy", "MMM dd hh:mm:ss yyyy"};
System.Globalization.CultureInfo provider = new System.Globalization.CultureInfo("en-US");

DateTime resultDate = new DateTime(1900,1,1);

foreach(string format in inputFormats)
{
	if (DateTime.TryParseExact(inputDate.Substring(4,inputDate.Length-4), format, provider, System.Globalization.DateTimeStyles.None, out resultDate))
	{
		Console.WriteLine("A result date is '{0}'", resultDate);
		break;
	}
} 


if(resultDate==new DateTime(1,1,1))
{
	Console.WriteLine("String to date conversion failed. Unknown format!");
}
 
Share this answer
 
v3
Comments
Karthik_Mahalingam 27-Sep-16 2:41am    
what about the input string in
1) Tue Aug 9 00:00:03 2016
2) Tue Aug 10 00:00:03 2016
Maciej Los 27-Sep-16 4:53am    
See updated answer.
Karthik_Mahalingam 27-Sep-16 5:00am    
Maciej,
am sorry, it looks complicated and using loop, not convincing.
however its upto OP.
Maciej Los 27-Sep-16 6:52am    
Well, as i mentioned, there's few ways to achieve that...
Cheers!
Maciej
Karthik_Mahalingam 27-Sep-16 6:58am    
hmm! cheers
:)

4, for your efforts
Add these lines,

C#
private static string ParseDateTime(string dateTime)
      {
          var parts = dateTime.Split(' ');
          var day = parts[2];
          var validDay = day.Length == 1 ? "0" + day : day;
          dateTime = dateTime.Replace(" " + day + " ", " " + validDay + " ");

          try
          {


The day you are passing is in "d" format, but you are parsing in "dd" format, so it has to be well formatted to dd for single digit numbers by adding 0 at prefix
 
Share this answer
 
v2
Comments
User1454 27-Sep-16 1:26am    
Thanks a ton!!! It worked . Modified to
var parts = dateTime.Split(' ');
var day = parts[2];
var validDay = day.Length == 1 ? "0" + day : day;
dateTime = dateTime.Replace(" " + day + " ", " " + validDay + " ");
dateValue = DateTime.ParseExact(dateTime, "ddd MMM dd HH:mm:ss yyyy", null);
UTC_DateTime = dateValue.ToString("yyyy-MM-dd HH:mm:ss");
Karthik_Mahalingam 27-Sep-16 1:28am    
cool
Maciej Los 27-Sep-16 2:37am    
Sorry, Karthik, but this solution is... low quality.
Please, see my answer.
Karthik_Mahalingam 27-Sep-16 2:42am    
Hi Maciej
i knew its not a perfect solution, but how to handle the day when less than 10 and greater than 9 ?
Maciej Los 27-Sep-16 2:51am    
Nothing ;)
It's quite simple to workaround it. I'll update my answer in few minutes.
A very simple method for your requirement :


C#
/// <summary>
   ///
   /// </summary>
   /// <param name="dateTime">input date format : "ddd MMM d HH:mm:ss yyyy"</param>
   /// <returns>output date format : "yyyy-MM-dd HH:mm:ss"</returns>
   private string ParseDateTime(string dateTime)
   {
       DateTime dateValue;
       string UTC_DateTime = "";
       try
       {
           //Tue Aug 9 00:00:03 2016  |  2016-08-09 00:00:03
           dateValue = DateTime.ParseExact(dateTime, "ddd MMM d HH:mm:ss yyyy", CultureInfo.InvariantCulture);
           UTC_DateTime = dateValue.ToString("yyyy-MM-dd HH:mm:ss");
           return UTC_DateTime;
       }
       catch (Exception ex)
       {
           return "";
       }
   }
 
Share this answer
 
Comments
Maciej Los 27-Sep-16 4:56am    
Please, read the comments to my answer. You should avoid to return string instead of DateTime.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900