DateTimeOffset.FromUnixTimeSeconds() Method in C#


The DateTimeOffset.FromUnixTimeSeconds() method in C# is used to convert a Unix time expressed as the number of seconds that have elapsed since 1970-01-01T00:00:00Z to a DateTimeOffset value.

Syntax

Following is the syntax −

public static DateTimeOffset FromUnixTimeSeconds (long val);

Above, the parameter value is a Unix time, expressed as the number of seconds that have elapsed since 1970-01-01T00:00:00Z (January 1, 1970, at 12:00 AM UTC).

Example

Let us now see an example to implement the DateTimeOffset.FromUnixTimeSeconds() method −

using System;
public class Demo {
   public static void Main() {
      DateTimeOffset offset = DateTimeOffset.FromUnixTimeSeconds(20);
      Console.WriteLine("DateTimeOffset = {0} ",offset);
      Console.WriteLine("DateTimeOffset (other format) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ",offset);
   }
}

Output

This will produce the following output −

DateTimeOffset = 1/1/1970 12:00:20 AM +00:00
DateTimeOffset (other format) = 01 January 1970, 12:00:20

Example

Let us now see another example to implement the DateTimeOffset.FromUnixTimeSeconds() method. For Unix times before this date, set the parameter value to be negative −

using System;
public class Demo {
   public static void Main() {
      DateTimeOffset offset = DateTimeOffset.FromUnixTimeSeconds(-20);
      Console.WriteLine("DateTimeOffset = {0} ",offset);
      Console.WriteLine("DateTimeOffset (other format) = {0:dd} {0:y}, {0:hh}:{0:mm}:{0:ss} ",offset);
   }
}

Output

This will produce the following output −

DateTimeOffset = 12/31/1969 11:59:40 PM +00:00
DateTimeOffset (other format) = 31 December 1969, 11:59:40
raja
Published on 06-Nov-2019 06:55:13
Advertisements