C# time calculation (2)

Table of contents

5. Time comparison

6. Time data conversion

7. Time interval calculation

8. Get network time

9. Timestamp

10. Time zone time

Finish


Overview
In C#, DateTime is a built-in class for handling dates and times, with values ​​ranging from 00:00:00 (midnight) to January 1, 0001. Anno Domini December 31, 11:59:59 pm (Gregorian calendar).

Time values ​​are measured in units of 100 nanoseconds, called ticks. A specific date is the number of clock cycles since 12:00 midnight on January 1, A.0001, (GregorianCalendar C.E.). This number does not include ticks added for leap seconds. For example, a tick value of 31241376000000000L represents Friday, January 1, 0100 12:00:00 midnight. DateTime values ​​are always expressed in the context of an explicit or default calendar.

C# Time Calculation (1)-CSDN Blog

5. Time comparison

If you want to compare two times, which one is earlier and which one is later, there are many methods, you can use TimeSpan, DateTime, DateTimeOffset, etc.

Example 1:

Directly use the greater than sign and less than sign operators to determine

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = DateTime.Parse("2023-11-24 19:30:23");
            DateTime dt2 = DateTime.Parse("2023-11-24 23:10:51");

            if(dt1 > dt2)
            {
                Console.WriteLine("dt1 时间大于 dt2");
            }
            else if(dt2 > dt1)
            {
                Console.WriteLine("dt2 时间大于 dt1");
            }
            else
            {
                Console.WriteLine("两个时间相同");
            }

            Console.ReadKey();
        }
    }
}

Effect:

Example 2:

Use CompareTo to determine which of two times is older and which is younger

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = DateTime.Parse("2023-11-24 19:30:23");
            DateTime dt2 = DateTime.Parse("2023-11-24 23:10:51");

            // 1 表示第一个时间晚于第二个时间,(时间1 大于 时间2)
            // 0 表示两个时间相等,
            //-1 表示第一个时间早于第二个时间(时间1 小于 时间2)
            int result = dt1.CompareTo(dt2);
            Console.WriteLine("结果:{0}", result);

            Console.ReadKey();
        }
    }
}

run:

Example 3:

Using DateTime.Compare has the same effect as Example 2

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = DateTime.Parse("2023-11-24 19:30:23");
            DateTime dt2 = DateTime.Parse("2023-11-24 23:10:51");

            // 1 表示第一个时间晚于第二个时间,(时间1 大于 时间2)
            // 0 表示两个时间相等,
            //-1 表示第一个时间早于第二个时间(时间1 小于 时间2)
            int result = DateTime.Compare(dt1, dt2);
            Console.WriteLine("结果:{0}", result);
            Console.ReadKey();
        }
    }
}

6. Time data conversion

Time data conversion refers to converting minutes to seconds, or seconds to hours, etc.

Now there is a question, we go to the cinema to watch a movie. If the movie is 280 minutes long, how many hours and how many minutes is it?

If we calculate manually, we usually use 280 / 60 to get the number of hours, and then 280 % 60 to get the number of minutes. However, it is not easy for most people to calculate 280 / 60. It is easier to use multiplication to calculate. 4 * 60 = 240, 280 - 240 = 40, which should be 4 hours and 40 minutes, so I will use code to solve this problem below.

Example 1:

Convert minutes to hours, minutes

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            TimeSpan timeSpan = TimeSpan.FromMinutes(280);
            Console.WriteLine(timeSpan);
            Console.ReadKey();
        }
    }
}

Effect:

Example 2:

I wrote a timer in C#. The timer requires me to calculate it in milliseconds. So what is the number of milliseconds in 1 hour?

Code:

Timer = new System.Timers.Timer();
Timer.Interval = TimeSpan.FromHours(1).TotalMilliseconds;
Timer.Elapsed += Timer_Elapsed;
Timer.AutoReset = true;

The above code is not complete, the focus is on TimeSpan.FromHours(1).TotalMilliseconds

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            double mills = TimeSpan.FromHours(1).TotalMilliseconds;
            Console.WriteLine("毫秒数:{0}", mills);
            Console.ReadKey();
        }
    }
}

Effect:

Example 3:

How many milliseconds is 12 minutes?

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            double mills = TimeSpan.FromMinutes(12).TotalMilliseconds;
            Console.WriteLine("毫秒数:{0}", mills);
            Console.ReadKey();
        }
    }
}

Effect:

7. Time interval calculation

You can use TimeSpan to determine how many seconds are between two times.

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = DateTime.Parse("2023-11-24 19:30:23");
            DateTime dt2 = DateTime.Parse("2023-11-24 23:10:51");
            TimeSpan timeSpan = dt2 - dt1;
            int seconds = (int)timeSpan.TotalSeconds;
            Console.WriteLine("两个时间之间间隔秒数:{0}", seconds);
            Console.ReadKey();
        }
    }
}

Effect:

You can also encapsulate the calculation of interval time and create a new class TimeInterval

using System;

/// <summary>
/// 时间差计算
/// </summary>
public class TimeInterval
{
    /// <summary>
    /// 计算两个时间间隔的时长
    /// </summary>
    /// <param name="TimeType">返回的时间类型</param>
    /// <param name="StartTime">开始时间</param>
    /// <param name="EndTime">结束时间</param>
    /// <returns>返回间隔时间,间隔的时间类型根据参数 TimeType 区分</returns>
    public static double GetSpanTime(TimeType TimeType, DateTime StartTime, DateTime EndTime)
    {
        TimeSpan ts1 = new TimeSpan(StartTime.Ticks);
        TimeSpan ts2 = new TimeSpan(EndTime.Ticks);
        TimeSpan ts = ts1.Subtract(ts2).Duration();
        double result = 0f;
        switch (TimeType)
        {
            case TimeType.MilliSecond:
                result = ts.TotalMilliseconds;
                break;
            case TimeType.Seconds:
                result = ts.TotalSeconds;
                break;
            case TimeType.Minutes:
                result = ts.TotalMinutes;
                break;
            case TimeType.Hours:
                result = ts.TotalHours;
                break;
            case TimeType.Days:
                result = ts.TotalDays;
                break;
        }
        return result;
    }
    
    private TimeInterval() { }
}

/// <summary>
/// 时间类型
/// </summary>
public enum TimeType
{
    /// <summary>
    /// 毫秒
    /// </summary>
    MilliSecond,
    /// <summary>
    /// 秒
    /// </summary>
    Seconds,
    /// <summary>
    /// 分钟
    /// </summary>
    Minutes,
    /// <summary>
    /// 小时
    /// </summary>
    Hours,
    /// <summary>
    /// 天
    /// </summary>
    Days,
    /// <summary>
    /// 月
    /// </summary>
    Months
}

transfer:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = DateTime.Parse("2023-11-24 19:30:23");
            DateTime dt2 = DateTime.Parse("2023-11-24 23:10:51");
            double seconds = TimeInterval.GetSpanTime(TimeType.Seconds, dt1, dt2);
            Console.WriteLine("两个时间之间间隔秒数:{0}", seconds);
            Console.ReadKey();
        }
    }
}

Effect:

8. Get network time

Obtaining network time mainly involves finding the corresponding server interface. If you have your own server, then it is very simple to implement. You can write a WebAPI interface yourself and use C# to send a get request to obtain the network time.

The current time can also be obtained through the following method. time.nist.gov is a foreign time verification interface. You can obtain the current Beijing time through the following method.

Example:

private static DateTime GetInternetDate()
{
    var client = new TcpClient("time.nist.gov", 13);
    using (var streamReader = new StreamReader(client.GetStream()))
    {
        var response = streamReader.ReadToEnd();
        var utcDateTimeString = response.Substring(7, 17);
        var localDateTime = DateTime.ParseExact(utcDateTimeString, "yy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal);
        return localDateTime;
    }
}

In addition, I searched Baidu for the keyword "C# Get Network Time" and found many posts about getting Baidu Network Time. I tried it and it can return the current time, but it is not very stable and often gets stuck. If you frequently When requesting, sometimes the data is not returned, and the experience is not particularly good, so I won’t post the code here.

For the corresponding usage of Get Post, you can refer to my post

C# Http request interface Get / Post Xiong Siyu’s blog-CSDN blog

9. Timestamp

A timestamp refers to a numeric value that represents a specific point in time. It is usually calculated as the number of seconds or milliseconds that have elapsed since some specific starting time (such as January 1, 1970 UTC).

The uses of timestamps:

1. Cross-platform time representation: Timestamp is a cross-platform time representation because it is a numeric value and is not restricted by time zones and formats. Timestamps can be sent to other systems or applications and interpreted and converted in different environments.

2. Time calculation and comparison: By using timestamps, time calculation and comparison can be easily performed. You can convert timestamps to datetime objects and perform various datetime operations such as addition, subtraction, comparison, and formatting.

3. Persistent storage: Timestamps are often used to record the time when an event occurred in a database or log file. Storing timestamps as numeric values ​​is more efficient than storing datetime objects, and allows for easy sorting and querying.

Convert time to seconds, milliseconds

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 将当前时间转换为时间戳(秒数)
            DateTimeOffset now = DateTimeOffset.Now;
            long timestampSeconds = now.ToUnixTimeSeconds();
            Console.WriteLine("timestampSeconds: {0}", timestampSeconds);

            // 将当前时间转换为时间戳(毫秒数)
            long timestampMilliseconds = now.ToUnixTimeMilliseconds();
            Console.WriteLine("timestampMilliseconds: {0}", timestampMilliseconds);

            Console.ReadKey();
        }
    }
}

Effect:

Convert timestamp to date

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 将当前时间转换为时间戳(秒数)
            DateTimeOffset now = DateTimeOffset.Now;
            long timestampSeconds = now.ToUnixTimeSeconds();

            // 将当前时间转换为时间戳(毫秒数)
            long timestampMilliseconds = now.ToUnixTimeMilliseconds();

            // 将时间戳(秒数)转换回日期时间对象
            DateTimeOffset dateTimeFromSeconds = DateTimeOffset.FromUnixTimeSeconds(timestampSeconds);
            Console.WriteLine("dateTimeFromSeconds: {0}", dateTimeFromSeconds);
            // 将时间戳(毫秒数)转换回日期时间对象
            DateTimeOffset dateTimeFromMilliseconds = DateTimeOffset.FromUnixTimeMilliseconds(timestampMilliseconds);
            Console.WriteLine("dateTimeFromMilliseconds: {0}", dateTimeFromMilliseconds);

            Console.ReadKey();
        }
    }
}

Effect:

10. Time zone time

Now there is a question. If I am in China and want to know what time it is in the United States, how can I calculate it? In fact, there is no need to calculate. Just get the current time in the United States directly through the code. You can also calculate the current time in the United States based on your current time and add the time difference.

Example 1:

Use the time difference to calculate the U.S. time corresponding to the current Beijing time.

American time is 13 hours behind ours. Just get the local time in Beijing and then subtract 13 hours to get the American time.

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            DateTime dt1 = DateTime.Now;
            DateTime dt2 = dt1.AddHours(-13);
            Console.WriteLine("美国时间是:{0}", dt2);
            Console.ReadKey();
        }
    }
}

Effect:

Since the console time has not been updated, it took a few seconds to take the screenshot, which is not much different from the seconds on the web page, haha.

Example 2:

Get US time

Code:

namespace Test2
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 获取当前的本地时间
            DateTime localTime = DateTime.Now;
            // 将本地时间转换为美国东部时间
            TimeZoneInfo easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
            DateTime easternTime = TimeZoneInfo.ConvertTime(localTime, easternTimeZone);
            // 打印美国当前时间
            Console.WriteLine("美国当前时间:{0}", easternTime);

            Console.ReadKey();
        }
    }
}

Effect:

In the above code, you can see that the US time is obtained using this code

TimeZoneInfo easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

So how do you get the time in other countries? The string inside the FindSystemTimeZoneById method is used to obtain the time based on the region. If you want to obtain the time in other countries or regions, just change this string.

For example:

Get the current time in Argentina. The characters corresponding to the time in Argentina are Argentina Standard Time.

Code:

namespace Test1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 获取当前的本地时间
            DateTime localTime = DateTime.Now;
            TimeZoneInfo easternTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Argentina Standard Time");
            DateTime easternTime = TimeZoneInfo.ConvertTime(localTime, easternTimeZone);
            Console.WriteLine("阿根廷当前时间:{0}", easternTime);

            Console.ReadKey();
        }
    }
}

Effect:

There is still a little time difference between this and the website. I don’t know why, so I’ll leave it at that for now.

Time zone characters for:

Dateline Standard Time - International Dateline Standard Time
UTC-11 - UTC-11
Samoa Standard Time - Samoa Islands Standard Time< /span> Iran Standard Time - Iran Standard Time Russian Standard Time - Russian Standard Time Arab Standard Time - Arab (Arab) Standard Time Arabic Standard Time - Arabic (Arabic) Standard Time E. Africa Standard Time - East African Standard Time GTB Standard Time - GTB Standard Time FLE Standard Time - FLE Standard Time Middle East Standard Time - Middle East Standard Time Israel Standard Time - Jerusalem Standard Time E. Europe Standard Time - Eastern European Standard Time Egypt Standard Time - Egypt Standard Time Jordan Standard Time - Jordan Standard Time Syria Standard Time - Syria Standard Time South Africa Standard Time - South Africa Standard Time W. Europe Standard Time - Western European Standard Time Central Europe Standard Time - Central European Standard Time Central European Standard Time - Central Europe Standard Time Namibia Standard Time - Namibia Standard Time Romance Standard Time - Rome Standard Time W. Central Africa Standard Time - West Central Africa Standard Time GMT Standard Time - GMT Standard Time Greenwich Standard Time - Greenwich Standard Time Morocco Standard Time - Morocco Standard Time UTC - Coordinated Universal Time Cape Verde Standard Time - Cape Verde Islands Standard Time Azores Standard Time - Azores Standard Time UTC-02 - UTC-02 Mid-Atlantic Standard Time - Mid-Atlantic Standard Time Canada Central Standard Time - Canada Central Standard Time< /span> Greenland Standard Time - Greenland Standard Time Argentina Standard Time - Argentina Standard Time E. South America Standard Time - Eastern South America Standard Time SA Eastern Standard Time - South America Eastern Standard Time Newfoundland Standard Time - Newfoundland Standard Time Central Brazilian Standard Time - Brazil Central Standard Time Atlantic Standard Time - Atlantic Standard Time Pacific SA Standard Time - Pacific South America Standard Time Paraguay Standard Time - Paraguay Standard Time SA Western Standard Time - South America Western Standard Time Venezuela Standard Time - Venezuela Standard Time SA Pacific Standard Time - South America Pacific Standard Time US Eastern Standard Time - United States Eastern Standard Time Eastern Standard Time - Eastern Standard Time Central Standard Time (Mexico) - Central Standard Time (Mexico) Central Standard Time - Central Standard Time Central America Standard Time - Central America Standard Time Mountain Standard Time - Mountain Standard Time Mountain Standard Time ( Mexico) - Mountain Standard Time (Mexico) US Mountain Standard Time - United States Mountain Standard Time Pacific Standard Time - Pacific Standard Time Pacific Standard Time (Mexico) - Pacific Standard Time (Mexico) Alaskan Standard Time - Alaska Standard Time
Hawaiian Standard Time - Hawaiian Standard Time Azerbaijan Standard Time - Azerbaijan Standard Time Georgian Standard Time - Georgian Standard Time Mauritius Standard Time - Mauritius Standard Time Arabian Standard Time - Arabian Peninsula Standard Time Afghanistan Standard Time - Afghanistan Standard Time



























































Pakistan Standard Time - Pakistan Standard Time
Ekaterinburg Standard Time - Yekaterinburg Standard Time
West Asia Standard Time - West Asia Standard Time< a i=3> Sri Lanka Standard Time - Sri Lanka Standard Time India Standard Time - India Standard Time Nepal Standard Time - Nepal Standard Time N. Central Asia Standard Time - Central Asia North Standard Time Bangladesh Standard Time - Bangladesh Standard Time Central Asia Standard Time - Central Asia Standard Time Myanmar Standard Time - Myanmar Standard Time North Asia Standard Time - North Asia Standard Time SE Asia Standard Time - Southeast Asia Standard Time Ulaanbaatar Standard Time - Ulaanbaatar Standard Time North Asia East Standard Time - North Asia Eastern Standard Time China Standard Time - China Standard Time Taipei Standard Time - Taipei Standard Time Singapore Standard Time - Peninsular Malaysia Standard Time W . Australia Standard Time - Western Australia Standard Time Tokyo Standard Time - Tokyo Standard Time Yakutsk Standard Time - Yakutsk Standard Time Korea Standard Time - Korea Standard Time AUS Central Standard Time - Australia Central Standard Time Cen. Australia Standard Time - Central Australia Standard Time a> UTC+12 - UTC+12 Fiji Standard Time - Fiji Standard Time< /span> Tonga Standard Time - Tonga Standard Time Kamchatka Standard Time - Kamchatka Standard Time New Zealand Standard Time - New Zealand Standard Time Magadan Standard Time - Magadan Standard Time Central Pacific Standard Time - Central Pacific Standard Time Tasmania Standard Time - Tasmania Island Standard Time Vladivostok Standard Time - Vladivostok (Vladivostok) Standard Time E. Australia Standard Time - Eastern Australia Standard Time AUS Eastern Standard Time - Australia Eastern Standard Time West Pacific Standard Time - Pacific Western Standard Time































Finish

If this post is helpful to you, please follow + like + leave a message

end

Guess you like

Origin blog.csdn.net/qq_38693757/article/details/134602108