Click here to Skip to main content
15,894,017 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
As part of an application I am making, I get a few times from an XML file online and display them in individual labels. The problem is that the times from the file are not in the format that I want so I was wondering if there is any way to convert the string to a custom format.

The times I am getting are like this:
2013-09-04T14:00:00Z
And I want to display them like this:
04/09/2013 1400

Is there any way I can easily do this, there will be a few of these so it should ideally be in one line of code, just so I can easily convert to a time I want. Thank you.
Posted
Comments
[no name] 5-Sep-13 11:54am    
http://msdn.microsoft.com/en-us/library/w2sa9yss.aspx
Philippe Mori 5-Sep-13 19:54pm    
I think that DateTime will correctly parse time as you have in XML file without needing to specify the format and generally, you want to format time according to user preference (Windows current date/time format). Again, tou can have it directly by calling ToString().
BillWoodruff 6-Sep-13 2:51am    
You are using WinForms ? WPF ? ASP.Net ? Please clarify.

The first step is to convert the string to a DateTime. This is done by calling http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx. Then format the DateTime object in any form you want as shown here: http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx[^].

/ravi
 
Share this answer
 
 
Share this answer
 
You can define a string extension method, like:
C#
public static class MyExtensions
{
  public static string DateTimeConvert( this string source, string destFormat )
  {
    DateTime dateTime;
    if ( DateTime.TryParse( source, out dateTime ) )
    {
      return dateTime.ToString( destFormat );
    }
    return null;
  }
}

Usage:
C#
static void MyCode()
{
  const string source = "2013-09-04T14:00:00Z";
  Console.WriteLine( "DateTime : " + source.DateTimeConvert( "MM/dd/yyyy hhmm" ) );
}
 
Share this answer
 

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