convert datetime to utc in csharp

To convert a DateTime object to UTC in C#, you can use the ToUniversalTime() method of the DateTime struct.

Here's an example:

main.cs
DateTime dateTime = DateTime.Now; // current local time
DateTime utcDateTime = dateTime.ToUniversalTime(); // converted to UTC
127 chars
3 lines

In this example, the dateTime object is the current local time, and the utcDateTime object is the same time, converted to UTC.

Keep in mind that this method uses the system's time zone settings to perform the conversion. If you need to convert to a specific time zone, you can use the TimeZoneInfo class, like this:

main.cs
DateTime dateTime = DateTime.Now; // current local time
TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
DateTime convertedDateTime = TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone); // converted to the specified timezone's UTC offset
274 chars
4 lines

In this example, timeZone is a TimeZoneInfo object that represents the Pacific Standard Time zone. The ConvertTimeToUtc() method takes the local time (dateTime) and the time zone (timeZone) and returns the corresponding UTC time (convertedDateTime).

gistlibby LogSnag