简体   繁体   English

通过查询字符串传递 C# DateTime

[英]Passing a C# DateTime via the Query String

I have a C# DateTime object.我有一个 C# DateTime 对象。 This object includes both the date and time.该对象包括日期和时间。 I need to pass this information to a REST-based service.我需要将此信息传递给基于 REST 的服务。 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,以便我可以通过查询字符串传递它,并将其解析回服务器端的 DateTime?

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,谢谢,

Just use ToString() and pass a format eg: startDate.ToString("yyyyMMddHHmmss")只需使用 ToString() 并传递一个格式,例如: startDate.ToString("yyyyMMddHHmmss")

And parse it back by using DateTime.ParseExact()并使用DateTime.ParseExact()解析它

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.这将为您提供符合 ISO 8601 的格式,并且使用 UTC 将确保不存在时区等问题。

Only drawback is that it doesn't look as "nice" as a simple "yyyyMMdd".唯一的缺点是它看起来不像简单的“yyyyMMdd”那么“好”。

I'd use yyyyMMdd as the format;我会使用yyyyMMdd作为格式; doesn't need to be URL encoded and it's easy to read/understand.不需要进行 URL 编码,并且易于阅读/理解。

On the server side, you'd have to call DateTime.ParseExact(dateString, "yyyyMMdd") to get the date out.在服务器端,您必须调用DateTime.ParseExact(dateString, "yyyyMMdd")来获取日期。

Hope this helps.希望这可以帮助。

string s = DateTime .字符串 s = DateTime ToString (" yyyyMMddHHmmssfff ") ToString (" yyyyMMddHHmmssfff ")

Note: fff is milliseconds (you may remove the 'fff' if it is not needed)注意:fff 是毫秒(如果不需要,您可以删除 'fff')
Then convert it back to DateTime using然后使用将其转换回 DateTime

DateTime d = DateTime .日期时间 d = DateTime ParseExact (s, " yyyyMMddHHmmssfff ", CultureInfo . InvariantCulture ) ParseExact (s, " yyyyMMddHHmmssfff ", CultureInfo . InvariantCulture )

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

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