Passing a C# DateTime via the Query String

2020-05-24 20:15发布

I have a C# DateTime object. This object includes both the date and time. I need to pass this information to a REST-based service. My question is, how do I format the DateTime, such that I can pass it via the query string, and parse it back into a DateTime on the server-side?

DateTime startDate = GetStartDate();
string url = "http://www.mydomain.com/myservice.svc/[startDateGoesHere]

WebRequest request = HttpWebRequest.Create(url);
request.BeginGetResponse(new AsyncCallback(Service_Completed), request);

Thank you,

标签: c# .net datetime
4条回答
▲ chillily
2楼-- · 2020-05-24 20:40

For accuracy and consistency you could use:

string utcDateOut = DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture);

DateTime utcDateIn = DateTime.ParseExact(utcDateOut, "s", 
                              CultureInfo.InvariantCulture, 
                              DateTimeStyles.AdjustToUniversal);

This will give you an ISO 8601 compliant format and the use of UTC will ensure that there are no issues with time zones etc.

Only drawback is that it doesn't look as "nice" as a simple "yyyyMMdd".

查看更多
欢心
3楼-- · 2020-05-24 20:42

Just use ToString() and pass a format e.g.: startDate.ToString("yyyyMMddHHmmss")

And parse it back by using DateTime.ParseExact()

查看更多
Lonely孤独者°
4楼-- · 2020-05-24 20:54

I'd use yyyyMMdd as the format; doesn't need to be URL encoded and it's easy to read/understand.

On the server side, you'd have to call DateTime.ParseExact(dateString, "yyyyMMdd") to get the date out.

Hope this helps.

查看更多
倾城 Initia
5楼-- · 2020-05-24 20:59

string s = DateTime.ToString("yyyyMMddHHmmssfff")

Note: fff is milliseconds (you may remove the 'fff' if it is not needed)
Then convert it back to DateTime using

DateTime d = DateTime.ParseExact(s, "yyyyMMddHHmmssfff", CultureInfo.InvariantCulture)

查看更多
登录 后发表回答