简体   繁体   中英

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

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?

Thanks in advance

A DateTime value doesn't know anything its formatting (and indeed it shouldn't ). It sounds like your web service is broken if it's not accepting standard date/time formatting. What's the implementation of the web service? 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 date = ..;
WebMethod(date.ToString("dd/MM/yyyy"));

Does the WebService accept the date as only "12/09/2010"? Typically a webservice should follow the reccomendations here XML Schema Part 2: Datatypes Second Edition

Which is UTC format. Using:

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

solves the problem most times.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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