C#日期时间格式更改 [英] C# datetime format change

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

问题描述

我想将"dd/mm/yyyy hh:mm:ss AM/PM" 的datetime.now格式转换为美国时间格式,即"mm-dd-yyyy hh:mm:ss AM/PM" .此外,我希望转换后的格式不以字符串形式显示为datetime,因为相同的格式存储在数据库中,并且数据库中的字段为datetime格式,因此它不会采用字符串格式.请建议....

I want to convert datetime.now format which is "dd/mm/yyyy hh:mm:ss AM/PM" to US time format i.e. "mm-dd-yyyy hh:mm:ss AM/PM". More over i want the converted format as datetime not in string because the same is being stored in the database and the field in the database is in datetime format so it will not take string.Please suggest....

推荐答案

DateTime 没有格式. DateTime.Now 没有格式,并且如果您进行任何形式的转换,如果您具有 DateTime ,则没有格式.格式的概念仅在您与字符串进行转换时适用-并且 DateTime.Now DateTime ,而不是 string

A DateTime value doesn't have a format. DateTime.Now doesn't have a format, and if you do any kind of conversion, if you've got a DateTime, there's no format. The concept of a format only applies when you're converting to or from a string - and DateTime.Now is a DateTime, not a string.

只需使用 DateTime.Now (或 DateTime.UtcNow )将值插入数据库,即可保存 data 重要的部分.

Just insert the value into the database using DateTime.Now (or DateTime.UtcNow) and you'll preserve the data which is the important part.

仅在实际拥有时才应执行字符串转换-此时,您可以使用自定义日期/时间格式字符串.(对于用户输入,请使用 TryParseExact ;对于实际上有效的机器输入,请使用

You should only perform string conversions when you actually have to - at which point you can use DateTime.TryParseExact and DateTime.ToString using custom date/time format strings. (Use TryParseExact for user input; for machine input which really should be valid, use DateTime.ParseExact.)

请注意,通常使用具有不变文化的自定义日期/时间模式或.

Note that it's usually a good idea to use custom date/time patterns with the invariant culture, or standard date/time patterns with "real" cultures (e.g. the user's culture).

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

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