Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to get a formatted string to represent UTC offset? [duplicate]

I need to format a date like so: 20110202192008-0500. The following code does the trick but I was wondering if there is a better/cleaner way to do this in c# 3.5. Thanks!!

  var date = DateTime.Now;
  var strDate = TimeZoneInfo.ConvertTimeToUtc(date).ToString("yyyyMMddHHmmss");
  var offsetHours = TimeZoneInfo.Local.GetUtcOffset(date).Hours.ToString("00");
  var offsetMinutes = TimeZoneInfo.Local.GetUtcOffset(date).Minutes.ToString("00");
  Console.Write(string.Concat(strDate, offsetHours, offsetMinutes));
like image 640
Mike Avatar asked Feb 02 '11 19:02

Mike


3 Answers

Here are some extension methods that will work in both .Net 3.5 and .Net 4.0 that will do exactly what you are asking in a very straight-forward way:

public static string ToStringWithOffset(this DateTime dt)
{
  return new DateTimeOffset(dt).ToStringWithOffset();
}

public static string ToStringWithOffset(this DateTime dt, TimeSpan offset)
{
  return new DateTimeOffset(dt, offset).ToStringWithOffset();
}

public static string ToStringWithOffset(this DateTimeOffset dt)
{
  string sign = dt.Offset < TimeSpan.Zero ? "-" : "+";
  int hours = Math.Abs(dt.Offset.Hours);
  int minutes = Math.Abs(dt.Offset.Minutes);

  return string.Format("{0:yyyyMMddHHmmss}{1}{2:00}{3:00}", dt, sign, hours, minutes);
}

You can now call these on any DateTime or DateTimeOffset you wish. For example:

string s = DateTime.Now.ToStringWithOffset();

or

string s = DateTimeTimeOffset.Now.ToStringWithOffset();

or

TimeSpan offset = TimeZoneInfo.Local.GetUtcOffset(someDate);
string s = someArbitraryTime.ToStringWithOffset(offset);

or any other number of ways you can think of.

like image 51
Matt Johnson-Pint Avatar answered Oct 04 '22 16:10

Matt Johnson-Pint


How about this:

.NET 4

 var utcOffset = TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
 Console.WriteLine(DateTime.UtcNow.ToString("yyyyMMddHHmmss") + ((utcOffset < TimeSpan.Zero) ? "-" : "+") + utcOffset.ToString("hhmm"));

.NET 3.5

 var utcAlmostFormat = DateTime.UtcNow.ToString("yyyyMMddHHmmss") + TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now);
 var utcFormat = System.Text.RegularExpressions.Regex.Replace(utcAlmostFormat, @"(\d\d):(\d\d):(\d\d)",@"$1$2");
 Console.WriteLine(utcFormat);

Go Steelers (from a guy in the Strip)

like image 26
SwDevMan81 Avatar answered Oct 04 '22 14:10

SwDevMan81


If you have a DateTimeOffset, the custom specifier zzz will output the timezone offset, though in the more standard "+HH:mm" format. If you don't want the colon, a string replace will do the trick.

Debug.WriteLine(DateTimeOffset.Now.ToString("yyyyMMddHHmmsszzz").Replace(":", ""));
// Result: "20110202153631-0500"
like image 21
David Yaw Avatar answered Oct 04 '22 16:10

David Yaw