简体   繁体   English

如何在C#中执行Convert.ToDateTime或解析日期,但在C#2.0中仅获得dd / mm / yyyy?

[英]How to do Convert.ToDateTime or parse date in C# but only get dd/mm/yyyy in C# 2.0?

As topic says, I have a string like 正如主题所说,我有一个像

string CreatedDate = "12/09/2010"

and I want to pass it to a web method that only accepts it as DateTime 我想将其传递给仅将其作为DateTime接受的Web方法

customer.dateCreated = Convert.ToDateTime(CreatedDate);

naturally it add hh:mm:ss after the date which the web service doesn't accept so how can I keep the date in the short format when I convert it to a date? 自然地,它在Web服务不接受的日期之后添加hh:mm:ss,所以当我将日期转换为日期时,如何将日期保持为短格式?

Thanks in advance 提前致谢

A DateTime value doesn't know anything its formatting (and indeed it shouldn't ). DateTime值不知道其格式(实际上也不应该 )。 It sounds like your web service is broken if it's not accepting standard date/time formatting. 如果不接受标准的日期/时间格式,听起来您的Web服务已损坏。 What's the implementation of the web service? Web服务的实现是什么? Is "customer" an autogenerated proxy class? “客户”是自动生成的代理类吗?

DateTime具有.Date属性,该属性会剥离时间信息。

Assuming you have: 假设您有:

void WebMethod(DateTime date);

and

string dateString = "12/09/2010";

then do next: 然后执行下一步:

DateTime date;
if (DateTime.TryParseExact(dateString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
    WebMethod(date);
}
else
{
    // raise an error - specified date is not in specified format
}

Note: 注意:

date.Hour // 0
date.Minute // 0
date.Seconds // 0

Otherwise, if you have DateTime object and WebMethod(string date) where date should be in specified format, then: 否则,如果您具有DateTime对象和WebMethod(string date) ,而date应该采用指定的格式,则:

DateTime date = ..;
WebMethod(date.ToString("dd/MM/yyyy"));

Does the WebService accept the date as only "12/09/2010"? WebService是否接受仅“ 12/09/2010”作为日期? Typically a webservice should follow the reccomendations here XML Schema Part 2: Datatypes Second Edition 通常,Web服务应遵循此处的建议XML模式第2部分:数据类型第二版

Which is UTC format. 这是UTC格式。 Using: 使用方法:

DateTime.ParseExact(value, "ddd MMM dd HH:mm:ss zz00 yyyy", null);

solves the problem most times. 大多数时候解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM