日期时间转换为字符串 [英] Converting DateTime to string
问题描述
我要转换的DateTime
到字符串
。
检查低于code。
命名空间TestDateConvertion
{
类节目
{
静态无效的主要(字串[] args)
{
对象值=新的日期时间(2003,12,23,6,22,30);
DateTime的结果=(日期时间)值;
Console.WriteLine(result.ToString(DD / MM / YYYY));
到Console.ReadLine();
}
}
}
我已经改变了我的系统日期格式,法罗语。
和我得到的输出为
23-12-2013
我应该如何获得作为输出?
23/12/2013
和考虑这个另一种情况下, 假设,我有一个Customculture信息,我想转换我的约会WRT我的风俗文化, 我在做什么之前,情况如下,
的String.Format(customCulture,{0:绿},结果);
现在我怎能让使用customCulture字符串的日期时间,它不应该依赖于系统日期时间?
看起来像你的文化的日期分隔符是 -
和蒂姆<一个href="http://stackoverflow.com/questions/17526239/converting-datetime-to-string#comment25485437_17526239">pointed, /
替换其本身吧。
您应该使用<一个href="http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo.invariantculture.aspx"><$c$c>CultureInfo.InvariantCulture$c$c>在你的 result.ToString()
方法的第二个参数。
获取CultureInfo对象就是文化无关(不变)。
对象值=新的日期时间(2003,12,23,6,22,30);
DateTime的结果=(日期时间)值;
Console.WriteLine(result.ToString(DD / MM / YYYY,CultureInfo.InvariantCulture));
输出会;
23/12/2003
下面一个 DEMO 。
I want to convert DateTime
to String
.
check the below code.
namespace TestDateConvertion
{
class Program
{
static void Main(string[] args)
{
object value = new DateTime(2003,12,23,6,22,30);
DateTime result = (DateTime)value;
Console.WriteLine(result.ToString("dd/MM/yyyy"));
Console.ReadLine();
}
}
}
I have changed my system date format to Faeroese.
and I am getting the output as
23-12-2013
How should I get the output as ?
23/12/2013
And consider this another scenario, suppose, i have a Customculture Info , and i want to convert my date w.r.t my custom culture, what i was doing before was as follows,
string.Format(customCulture, "{0:G}", result);
now how shall i get the datetime in string using customCulture and it should not depend on system DateTime?
Looks like your culture's date separator is -
and as Tim pointed, /
replaces itself with it.
You should use CultureInfo.InvariantCulture
as a second parameter in your result.ToString()
method.
Gets the CultureInfo object that is culture-independent (invariant).
object value = new DateTime(2003, 12, 23, 6, 22, 30);
DateTime result = (DateTime)value;
Console.WriteLine(result.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
Output will be;
23/12/2003
Here a DEMO.
这篇关于日期时间转换为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!