• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
风拂晚柳
博客园    首页    新随笔    联系   管理    订阅  订阅

C#-----类DateTime的常用方法

1.TryParse(string s, out DateTime result)

   将日期和时间的指定字符串表示形式转换为其 System.DateTime 等效项,并返回一个指示转换是否成功的值

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string timeStr = "2019-03-22 10:16:25";
            if (DateTime.TryParse(timeStr, out DateTime beginTime))
            {
                Console.Write(beginTime);
            }
            else
            {
                Console.WriteLine("时间格式不正确!");
            }
            Console.ReadLine();
        }
    }
}

 2.Now

   获取一个 System.DateTime 对象,该对象设置为此计算机上的当前日期和时间,表示为本地时间

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dateTime = DateTime.Now;
            Console.WriteLine(dateTime);
            Console.ReadLine();
        }
    }
}

3.ToString(string format)

   使用指定的格式和当前区域性的格式约定将当前 System.DateTime 对象的值转换为它的等效字符串表示形式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            DateTime dateTime = DateTime.Now;
            string nowTime = dateTime.ToString("yy-MM-dd hh:mm:ss");
            Console.WriteLine(nowTime);
            Console.ReadLine();
        }
    }
}

 4.>(DateTime t1, DateTime t2)

     确定指定的 System.DateTime 是否晚于另一个指定的 System.DateTime

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DateTimeTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string beginTime = "2019-04-22 21:25:15";
            string endTime = "2019-04-01 00:00:00";
            DateTime.TryParse(beginTime, out DateTime bTime);
            DateTime.TryParse(endTime, out DateTime eTime);
            if (bTime > eTime)
            {
                Console.WriteLine("开始时间不能大于结束时间!");
            }
            Console.ReadLine();
        }
    }
}

 

posted @ 2019-03-22 11:12  风拂晚柳  阅读(747)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3