zoukankan      html  css  js  c++  java
  • 转换日期时间,让其显示更友好

    对于时间日期,有时我们希望以更友好的方式展示,比如几秒钟前,几分钟前,几小时前......

    这其中:
    1、需要判断输入日期的格式是否正确
    2、使用TimeSpan计日期时间之间的间隔,然后可以转换成秒、分钟,等等
    3、最后转换成秒、分钟、小时、天等,以整型显示

        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))
    
                {
    
                    //计算时间间隔
    
                    TimeSpan ts = DateTime.Now - t;
    
                    //转换成分钟
    
                    double m = ts.TotalMinutes;
    
                    if (m < 1)
    
                    {
    
                        double s = m*60;
    
                        return (int)Math.Floor(s) + "秒钟前";
    
                    }
    
                    else if (m < 60)
    
                    {
    
                        return (int)Math.Floor(m) + "分钟前";
    
                    }
    
                    else if (m < 60 * 24)
    
                    {
    
                        double h = m/60;
    
                        return (int)Math.Floor(h) + "小时前";
    
                    }
    
                    else
    
                    {
    
                        double d = m/(60*24);
    
                        return (int)Math.Floor(d) + "天前";
    
                    }
    
                }
    
                else
    
                {
    
                    return "日期格式不符合";
    
                }
    
            }
    
        }
    
  • 相关阅读:
    linux常用命令
    练习00004
    python学习第六天
    练习00003
    练习00002
    python学习第四天
    练习00001
    Linux_安装mysql踩坑日记
    Linux_更改远程登录端口以及禁止root用户登录
    redis_基础_基本使用
  • 原文地址:https://www.cnblogs.com/darrenji/p/4370786.html
Copyright © 2011-2022 走看看