本文介绍了如何自定义日期时间格式或日期时间转换为字符串格式要求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在24小时格式的时间字符串。2009-12-31T23:59:59
结果我想在这种格式。2009/12/31 23:59: 59,即:MM / DD / YYYY HH:MM:SS搜索结果
当我试图把它隐蔽字符串我收到2009/12/31下午11:59:59 ..虽然我写的字串处理的代码 ..它似乎并没有要成为最糟糕的,当我有时间值,如高效的。而且案2009-1-1T1 :19:15。这里,作为字符串长度不同中,我甚至不能使用子()和convert.ToInt()追踪小时和几个月的价值..结果结果我使用Visual Studio 2005中,当我写这句话它抛出错误说无法隐式转换日期时间为字符串:
..结果

 结果= Convert.ToString(DATEVALUE); 



我简化我的问题:
是否有任何转换YYYY-MM-DDTHH方法:MM:SS的格式为MM / DD / YYYY HH:MM:SS
类的div =>运行 / DIV>

您需要使用ParseExact让它回到日期时间:

 字符串的FormatDateTime(字符串dateString){
DateTime的DT = DateTime.ParseExact(dateString,YYYY-MM-DDTHH:MM:SS,DateTimeFormatInfo.InvariantInfo,DateTimeStyles.None);
返回dt.ToString(MM / DD / YYYY HH:MM:SS);
}

这应该给你你正在寻找所需的输出。通过使用InvariantInfo,这将确保你的系统设置不与任何当前已在系统中定义替换斜线。我觉得我在你有一个评论看到了。被用作您的日期分隔符。





I have a DateTime string in 24 HOURS format .. "2009-12-31T23:59:59"
I want it in this format .. "12/31/2009 23:59:59" that is: "MM/DD/YYYY HH:MM:SS"

When I tried to covert it to string I am getting "12/31/2009 11:59:59 PM" .. though I can write a code for string manipulation .. it doesn't seem to be the efficient one .. Moreover the case become worst when I have dateTime value like "2009-1-1T1:19:15" .. here, as the string length is varying, I can't even trace the value of Hours and months using substring() and convert.ToInt() ..

I am using visual studio 2005, It is throwing error saying "Cannot implicitly convert DateTime to String" when I write this statement:..

result = Convert.ToString(dateValue);

I simplify my question:Is there any method to convert "yyyy-mm-ddThh:mm:ss" format to "mm/dd/yyyy hh:mm:ss" .. And it must work in visual studio 2005 ..

解决方案

You need to use ParseExact to get it back to datetime:

string FormatDateTime(string dateString) {
    DateTime dt = DateTime.ParseExact(dateString, "yyyy-MM-ddTHH:mm:ss", DateTimeFormatInfo.InvariantInfo, DateTimeStyles.None);
    return dt.ToString("MM/dd/yyyy HH:mm:ss");
}

That should give you the desired output you are looking for. By using InvariantInfo, it will make sure you system settings don't replace the slashes with whatever you have currently defined in the system. I think I saw in the comments that you had a "." being used as your date separator.

http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.dateseparator.aspxhttp://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.invariantinfo.aspx

这篇关于如何自定义日期时间格式或日期时间转换为字符串格式要求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 14:23