Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ToUnixTimeSeconds method missing after migration to VS 2017

var item = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();

The code causes the compilation error "Does not contain a definition for ToUnixTimeSeconds...". It works well in VS 2015, also I have using System; namespace and references to both mscorlib and System (4.0.0.0 version). Many other members of DateTimeOffset exist.

like image 937
Ilya Loskutov Avatar asked Apr 25 '17 09:04

Ilya Loskutov


2 Answers

(Editing based on Eric's comment)

Following APIs were added in .NET Framework 4.6; from release notes:

  • Support for converting dates and times to or from Unix time

    The following new methods have been added to the DateTimeOffset structure to support converting date and time values to or from Unix time:

    • DateTimeOffset.FromUnixTimeSeconds
    • DateTimeOffset.FromUnixTimeMilliseconds
    • DateTimeOffset.ToUnixTimeSeconds
    • DateTimeOffset.ToUnixTimeMilliseconds

You can also check the "Applies To" section in official docs to confirm compatibility: https://learn.microsoft.com/en-us/dotnet/api/system.datetimeoffset.tounixtimeseconds#applies-to

Just update your application target framework to framework version 4.6 or higher in project file (.csproj):

<PropertyGroup>
  <TargetFramework>net46</TargetFramework>
  <!--
    or multiple frameworks at once:
    <TargetFrameworks>net46,netstandard1.3</TargetFrameworks>
  -->
  ...
</PropertyGroup>

then in C# code:

public static long UnixTimeNowSec => DateTimeOffset.Now.ToUnixTimeSeconds();
like image 177
Kiratijuta Avatar answered Nov 13 '22 19:11

Kiratijuta


i recently i have the same problem in a new project. What i do after doing some google search and testing find a function like this one:

public static long ToUnixEpochDate(DateTime date) => new DateTimeOffset(date).ToUniversalTime().ToUnixTimeSeconds();

//Usage 
var now = DateTime.UtcNow;
var result = ToUnixEpochDate(now).ToString();

Hope it helps. Also try as @Kiratijuta mention in comment to target .net 4.6 or later.

like image 22
Jean Jimenez Avatar answered Nov 13 '22 19:11

Jean Jimenez