DateTimeOffset.ToOffset() Method in C#


The DateTimeOffset.ToOffset() method in C# is used to convert the value of the current DateTimeOffset object to the date and time specified by an offset value.

Syntax

Following is the syntax −

public DateTimeOffset ToOffset (TimeSpan val);

Above, the value is the offset to convert the DateTimeOffset value to.

Example

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

using System;
public class Demo {
   public static void Main() {
      DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 9, 10, 4, 20, 30, new TimeSpan(-5, 0, 0));
      Console.WriteLine("DateTimeOffset = {0}", dateTimeOffset);
      DateTimeOffset res = dateTimeOffset.ToOffset(new TimeSpan(-10, 1, 0));
      Console.WriteLine("DateTimeOffset (updated) = {0}", res);
   }
}

Output

This will produce the following output −

DateTimeOffset = 9/10/2019 4:20:30 AM -05:00
DateTimeOffset (updated) = 9/9/2019 11:21:30 PM -09:59

Example

Let us now see another example to implement the DateTimeOffset.ToOffset() method −

using System;
public class Demo {
   public static void Main() {
      DateTimeOffset dateTimeOffset = new DateTimeOffset(2019, 9, 10, 4, 20, 30, new TimeSpan(5, 0, 0));
      Console.WriteLine("DateTimeOffset = {0}", dateTimeOffset);
      DateTimeOffset res = dateTimeOffset.ToOffset(new TimeSpan(3, 1, 0));
      Console.WriteLine("DateTimeOffset (updated) = {0}", res);
   }
}

Output

This will produce the following output −

DateTimeOffset = 9/10/2019 4:20:30 AM +05:00
DateTimeOffset (updated) = 9/10/2019 2:21:30 AM +03:01

Updated on: 12-Nov-2019

494 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements