Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the equivalent of Java's SimpleDateFormat class in C#?

Tags:

java

c#

Anyone knows an equivalent class of Java's SimpleDateFormat in C#? I wonder if i can convert the following java code using Custom Date and Time Format Strings in C#

  SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); 
TimeZone tz = TimeZone.getDefault();
format.setTimeZone(TimeZone.getTimeZone("GMT"));
str = format.format(new Date());
like image 972
Xris Avatar asked Nov 12 '11 21:11

Xris


1 Answers

You can use DateTime's ToString() method and specify the custom format that you want the DateTime to be output in. In this case:

// US culture
var usCulture = new CultureInfo("en-US");
// Get current UTC time.   
var utcDate = DateTime.UtcNow;
// Change time to match GMT + 1.
var gmt1Date = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(utcDate, "W. Europe Standard Time");
// Output the GMT+1 time in our specified format using the US-culture. 
var str = gmt1Date.ToString("ddd, dd MMM yyyy HH:mm:ss z", usCulture);

Please note that .NET's equivalent of EEE is ddd.

like image 136
Johannes Kommer Avatar answered Sep 20 '22 09:09

Johannes Kommer