在C#中更改DateTime对象的格式并存储为DateTime对象 [英] Change format of DateTime object in c# and store back as DateTime object

查看:105
本文介绍了在C#中更改DateTime对象的格式并存储为DateTime对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将字符串2017-03-05转换为c#中的Datetime对象,格式为
yyyy-MM-dd

I want to convert string 2017-03-05 to Datetime object in c# in format yyyy-MM-dd

string startDate = "2017-03-05"; 
DateTime myDate = DateTime.ParseExact(startDate, "yyyy-MM-dd",
                         System.Globalization.CultureInfo.InvariantCulture);




myDate给了我05-03-2017 00:00:00

myDate gives me 05-03-2017 00:00:00

但是我想要myDate DateTime对象,例如2017-03-05 00:00:00,即yyyy-MM-dd格式。

But I want myDate DateTime object like 2017-03-05 00:00:00 i.e yyyy-MM-dd format.

推荐答案

将字符串解析为DateTime时,其格式为 no

When you parse your string to DateTime, it will have no format.

DateTime结构没有任何隐式格式。它只是具有基于长字段的日期和时间值,如 Ticks 。当您尝试获取格式概念的文本(也称为字符串)表示形式时,仅使用格式概念 。了解DateTime实例与格式化字符串表示形式之间的区别真的很重要。

DateTime structure does not have any implicit format. It just have date and time values which is based on long field as Ticks. Format concept only applies when you try to get it's textual (aka string) representation of it. It is really important to understand the difference between a DateTime instance and it's formatted string representation.

因此,如果您想获取DateTime的特定文本格式,则需要再次获得它的字符串表示形式。

So, if you wanna get a specific textual format of your DateTime, you will need to get it's string representation again.

string result = myDate.ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);

这篇关于在C#中更改DateTime对象的格式并存储为DateTime对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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