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

StackOverflow https://stackoverflow.com/questions/4255490

  •  27-09-2019
  •  | 
  •  

문제

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

도움이 되었습니까?

해결책

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"));

다른 팁

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 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top