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.ToDateTi开发者_Go百科me(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?
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"));
DateTime
has a .Date
property that strips the time information.
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.
精彩评论