将mm / dd / yyyy中的DateTime转换为yyyy-dd-mm中的DateTime [英] Convert DateTime in mm/dd/yyyy to DateTime in yyyy-dd-mm
问题描述
我正在尝试将 MM / dd / yyyy
中的 DateTime
转换为另一个 DateTime
在 yyyy-dd-MM
I am trying to convert from a DateTime
in MM/dd/yyyy
to another DateTime
in yyyy-dd-MM
我能够获得 string
格式为 yyyy-dd-MM
,使用 Date.Parse()。ToString( yyyy-MM-dd)
I was able to get a string
in form yyyy-dd-MM
by using Date.Parse().ToString("yyyy-MM-dd")
但是当我使用 Convert.ToDateTime()
或 Date.Parse()
将字符串
转换回 DateTime
,它只是将字符串
转换回 DateTime
形式, MM / dd / yyyy HH:mm:ss
But when I use Convert.ToDateTime()
or Date.Parse()
to convert the string
back to a DateTime
, it just converted the string
back to DateTime
form MM/dd/yyyy HH:mm:ss
推荐答案
说我要转换日期时间将日期格式格式化为其他格式在技术上是错误的,因为该格式是关于 DateTime
的字符串表示形式。
Saying I want to convert date time in some format to date time to some other format is technically wrong because the format is about string representation of DateTime
.
为什么我不能将 yyyy-dd-MM
格式的字符串转换为 DateTime
使用 DateTime.Parse()
?
Why can't I convert a string in yyyy-dd-MM
format to DateTime
using DateTime.Parse()
?
-
DateTime.Parse
使用当前区域性的约定来解析日期和时间字符串。
The
DateTime.Parse
parses a date and time string by using the conventions of the current culture.
要以跨机器和可能跨文化边界的自定义/固定格式解析日期和时间字符串,可以使用 DateTime.ParseExact
。
To parse a date and time string in a custom/fixed format across machine and possibly cultural boundaries, you can use DateTime.ParseExact
.
因此要将 yyyy-dd-MM
中的字符串转换为 DateTime
,您可以使用:
So to convert a string in yyyy-dd-MM
to DateTime
you can use:
var d = DateTime.ParseExact("2016-31-12", "yyyy-dd-MM", CultureInfo.InvariantCulture);
也如MSDN所述,因为日期和时间的字符串表示必须符合公认的模式,在调用parse方法解析用户输入时应始终使用异常处理,或者考虑使用 TryParse
或 TryParseExact
。
Also as mentioned in MSDN, because the string representation of a date and time must conform to a recognized pattern, you should always use exception handling when calling the parse method to parse user input or consider using TryParse
or TryParseExact
.
更多信息:
- DateTime.Parse
这篇关于将mm / dd / yyyy中的DateTime转换为yyyy-dd-mm中的DateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!