0

I have date time in a string as "20160127003500". What I need to do is convert this to Unix time-stamp adding hours to it.

I want to add hours offset as "1" or "2" or "24".

Can anyone please guide me in right direction.

Regards

Robin
  • 283
  • 4
  • 22
  • Just convert it to a regular DateTime and AddHours. There's plenty of guides on converting time all over SO. – Equalsk Jan 22 '16 at 17:10
  • 1
    That string looks like it's in `yyyyMMddHHmmss` format, which you can use with `DateTime.ParseExact`. However, you'll also need to know whether to interpret it as local time, UTC time, or time in some other time zone - because Unix time is UTC based. Without knowing the source time zone, you can't do it. – Matt Johnson-Pint Jan 22 '16 at 17:17
  • Please also clarify what exactly you mean by "I want to add hours offset". – Matt Johnson-Pint Jan 22 '16 at 17:19
  • @MattJohnson Thanks for replying the original timezone is CET, here is what the full string has "20160129205500 +0100". By hours offset I meant incrementing or subtracting number of hours from this time by passing an integer value. – Robin Jan 22 '16 at 18:22
  • Don't do that. Just use `DateTimeOffset.ParseExact`. I'm on my phone, but I'll post an example when I get back to a PC unless someone beats me to it. – Matt Johnson-Pint Jan 22 '16 at 18:31

1 Answers1

3

First, parse the entire string (including the offset you mentioned in the question comments) to a DateTimeOffset:

using System.Globalization;

string s = "20160129205500 +0100";
string format = "yyyyMMddHHmmss zzz";
DateTimeOffset dto = DateTimeOffset.ParseExact(s, format, CultureInfo.InvariantCulture);

Then, there are a few different ways to get a Unix timestamp. Note that by the pure definition of a "Unix timestamp", the result would be in terms of seconds, though many languages these days use a higher precision (such as milliseconds used in JavaScript).

If you are targeting .NET 4.6 or higher, simply use the built-in methods:

// pick one for the desired precision:
long timestamp = dto.ToUnixTimeMilliseconds();
long timestamp = dto.ToUnixTimeSeconds();

If you are targeting an earlier version of .NET, then compute it yourself:

DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

// pick one for the desired precision:
long timestamp = (long) dto.UtcDateTime.Subtract(epoch).TotalMilliseconds;
long timestamp = (long) dto.UtcDateTime.Subtract(epoch).TotalSeconds;
Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575