将字符串时间转换为其他格式 [英] Convert String Time to Other Format
问题描述
作为我正在制作的应用程序的一部分,我从在线XML文件中获取了几次并将其显示在单独的标签中。问题是文件的时间不是我想要的格式,所以我想知道是否有任何方法可以将字符串转换为自定义格式。
我得到的时间是这样的:
2013-09-04T14:00:00Z
我想要像这样显示它们:
04/09/2013 1400
我有什么方法可以轻松地做到这一点,其中一些是理想的,它应该在一行代码中,这样我就可以很容易地转换成我想要的时间。谢谢。
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.
推荐答案
第一步是将字符串转换为DateTime。这可以通过调用http://msdn.microsoft.com/en-us/library/system.datetime.tryparse.aspx来完成。然后以您想要的任何形式格式化DateTime对象,如下所示: http://msdn.microsoft .com / zh-CN / library / 8kb3ddd4.aspx [ ^ ]。
/ ravi
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
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx [ ^ ]
你可以定义字符串扩展方法,例如:
You can define a string extension method, like:
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:
static void MyCode()
{
const string source = "2013-09-04T14:00:00Z";
Console.WriteLine( "DateTime : " + source.DateTimeConvert( "MM/dd/yyyy hhmm" ) );
}
这篇关于将字符串时间转换为其他格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!