Convert the date and time to make it display more friendly and convert the date and time

Source: Internet
Author: User

Convert the date and time to make it display more friendly and convert the date and time

Sometimes we want to display the time and date in a more friendly way, such as a few seconds ago, a few minutes ago, a few hours ago ......

 

Here:
1. Check whether the format of the input date is correct.
2. Use TimeSpan to calculate the interval between date and time, and then convert it to seconds, minutes, and so on.
3. Convert the data to seconds, minutes, hours, and days.

 

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(LetTimeSay("2015-3-27"));
            Console.ReadKey();
        }
        static string LetTimeSay(string str)
        {
            DateTime t;
            if (DateTime.TryParse(str, out t))
            {
// Calculation Interval
                TimeSpan ts = DateTime.Now - t;
// Convert to minutes
                double m = ts.TotalMinutes;
                if (m < 1)
                {
                    double s = m*60;
Return (int) Math. Floor (s) + "seconds ago ";
                }
                else if (m < 60)
                {
Return (int) Math. Floor (m) + "Minutes Ago ";
                }
                else if (m < 60 * 24)
                {
                    double h = m/60;
Return (int) Math. Floor (h) + "Hours Ago ";
                }
                else
                {
                    double d = m/(60*24);
Return (int) Math. Floor (d) + "Days Ago ";
                }
            }
            else
            {
Return "the date format does not match ";
            }
        }
    }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.