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.
(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();
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.
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