Invalid ToUnixTimeSeconds method after migrating to VS 2017

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

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

+6
source share
3 answers

Recently, I have the same problem in a new project. What I do after doing a google search and testing, I will find a function like this:

 public static long ToUnixEpochDate(DateTime date) => new DateTimeOffset(date).ToUniversalTime().ToUnixTimeSeconds(); //Usage var now = DateTime.UtcNow; var result = ToUnixEpochDate(now).ToString(); 

Hope this helps.

+5
source

(Editing based on Eric's comment)

The following APIs have been added in the .NET Framework 4.6; from the release notes :

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

Just upgrade the target platform of your application to version 4.6 or higher in the 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(); 
+11
source

Make sure you are not using an older version of .NET such as 4.5. In older versions, System.DateTimeOffset does not contain the ToUnixTimeSeconds () method.

If so, and upgrading the .NET platform to a newer version will not change anything, this should solve the problem.

0
source

Source: https://habr.com/ru/post/1267126/


All Articles