C#日期时间转换 [英] c# datetime conversion

查看:70
本文介绍了C#日期时间转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

中具有值的字符串变量-2012年9月10日8:13:56 PM
它是MM/dd/yyyy hh:mm:ss tt格式

但我想将其转换为

dd/MM/yyyy hh:mm:ss tt

所以我的代码->

in have string variable with value -- 9/10/2012 8:13:56 PM
its a MM/dd/yyyy hh:mm:ss tt format

But i want to convert it to

dd/MM/yyyy hh:mm:ss tt

so my code-->

string strtime= getTime(Session["id"].ToString());
string format = "dd/MM/yyyy hh:mm:ss tt";
DateTime dt = DateTime.ParseExact(strtime, format, CultureInfo.InvariantCulture);
string str= dt.ToString(dd/MM/yyyy hh:mm:ss tt);




但它不起作用

例外:

字符串未被识别为有效的DateTime."
请帮忙!




but its not working

exception :

"String was not recognized as a valid DateTime."
Please help!

推荐答案

如果执行以下操作,如果可行...当然,您可能想要两个截然不同的信息,一个用于输入,另一个用于输出,如果您正在读/写很多日期.
If works if you do the following... of course, you might want to have two distinct infos, one for input and another to output, if you are reading/writing lots of dates.
// Create date time format info
System.Globalization.DateTimeFormatInfo info = 
    new System.Globalization.DateTimeFormatInfo();
            
// Change formats
info.ShortDatePattern = "MM/dd/yyyy";
info.LongTimePattern = "hh:mm:ss tt";

string input = "9/10/2012 8:13:56 PM";

// parse // or try parse if you prefer
DateTime datetime = DateTime.Parse(input, info);

// Change to output format
info.LongDatePattern = "dd/MM/yyyy";

// Get parsed datetime as string
string output = datetime.ToString("dd/MM/yyyy hh:mm:ss tt", info);



或者,如果您了解输入和输出区域性,则可以通过调用CultureInfo实例的"someCulture.DateTimeFormat"来获取格式.



Alternatively, if you know the input and output cultures, you can get the formats by calling "someCulture.DateTimeFormat" of the CultureInfo instances.


尝试一下...

Try this...

string strtime = "9/10/2012 8:13:56 PM ";
       // string format = "dd/MM/yyyy hh:mm:ss tt";
        DateTime dt = Convert.ToDateTime(strtime, ci);
        string str = dt.ToString();
        Response.Write(str);



谢谢



Thanks


如果我理解正确,会话中保存的值将采用MM/dd/yyyy hh:mm:ss tt格式.
因此,您在尝试执行DateTime.ParseExact时需要传递它.


If I understand correctly, the value saved in the session is in MM/dd/yyyy hh:mm:ss tt format.
Hence you need to pass that while trying to do DateTime.ParseExact.


string strtime= getTime(Session["id"].ToString());
string format = "MM/dd/yyyy hh:mm:ss tt";
DateTime dt = DateTime.ParseExact(strtime, format, CultureInfo.InvariantCulture);
string str= dt.ToString(dd/MM/yyyy hh:mm:ss tt);



希望有帮助(如果有的话),将其标记为答案/赞.
谢谢
Milind



Hope that helps, if it does, mark it as answer/upvote.
Thanks
Milind


这篇关于C#日期时间转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆