Passing a C# DateTime via the Query String

前端 未结 4 2154
猫巷女王i
猫巷女王i 2021-02-05 02:20

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,

4条回答
  •  没有蜡笔的小新
    2021-02-05 03:06

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

提交回复
热议问题