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));
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.
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)
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With