Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a date to a HTTP-formatted date in .Net / C#

Tags:

c#

.net

http

How does one convert a .Net DateTime into a valid HTTP-formatted date string?

like image 256
Gareth Jenkins Avatar asked Aug 16 '08 10:08

Gareth Jenkins


People also ask

How do I change the default date format in C#?

var ci = new CultureInfo("en-US"); ci. DateTimeFormat. ShortDatePattern = "MM/dd/yyyy"; app.

How do I change the date format from yyyy mm dd in C#?

string date = DateTime. ParseExact(SourceDate, "dd/MM/yyyy", CultureInfo. InvariantCulture). ToString("yyyy-MM-dd");


1 Answers

Dates can be converted to HTTP valid dates (RFC 1123) by using the "r" format string in .Net. HTTP dates need to be GMT / not offset - this can be done using the ToUniversalTime() method.

So, in C# for example:

string HttpDate = SomeDate.ToUniversalTime().ToString("r"); 

Right now, that produces HttpDate = "Sat, 16 Aug 2008 10:38:39 GMT"

See Standard Date and Time Format Strings for a list of .Net standard date & time format strings.

See Protocol Parameters for the HTTP date specification, and background to other valid (but dated) RFC types for HTTP dates.

like image 193
Gareth Jenkins Avatar answered Sep 18 '22 13:09

Gareth Jenkins