zoukankan      html  css  js  c++  java
  • JAVA对时间的操作

    1.Date获取当前时间

      1.1将时间毫秒转为日期格式。

     import java.sql.Date;
    Date d = new Date(System.currentTimeMillis());//传当前的毫秒时间
     String time=d.toLocaleString();//返回2015-8-17 11:08:26格式字符串
    
    //使用SimpleDateFormat转换需要的格式
    import java.text.SimpleDateFormat;
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); 
    System.out.println(sdf.format(longtime)); //输出2015-8-17 11:08:26

    1.2获取时间示例

    public void getTimeByDate(){
    Date date = new Date();
    DateFormat df1 = DateFormat.getDateInstance();//日期格式,精确到日
    System.out.println(df1.format(date));
    DateFormat df2 = DateFormat.getDateTimeInstance();//可以精确到时分秒
    System.out.println(df2.format(date));
    DateFormat df3 = DateFormat.getTimeInstance();//只显示出时分秒
    System.out.println(df3.format(date));
    DateFormat df4 = DateFormat.getDateTimeInstance(DateFormat.FULL,DateFormat.FULL); //显示日期,周,上下午,时间(精确到秒) 
    System.out.println(df4.format(date));  
    DateFormat df5 = DateFormat.getDateTimeInstance(DateFormat.LONG,DateFormat.LONG); //显示日期,上下午,时间(精确到秒) 
    
    System.out.println(df5.format(date));
    DateFormat df6 = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT); //显示日期,上下午,时间(精确到分) 
    System.out.println(df6.format(date));
    DateFormat df7 = DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.MEDIUM); //显示日期,时间(精确到分)
    System.out.println(df7.format(date));
    
      public void getTimeByCalendar(){
    Calendar cal = Calendar.getInstance()
    int year = cal.get(Calendar.YEAR);//获取年份
    int month=cal.get(Calendar.MONTH);//获取月份 
    int day=cal.get(Calendar.DATE);//获取日 
    int hour=cal.get(Calendar.HOUR);//小时 
    int minute=cal.get(Calendar.MINUTE);//
    int second=cal.get(Calendar.SECOND);//
    int WeekOfYear = cal.get(Calendar.DAY_OF_WEEK);//一周的第几天
    System.out.println("现在的时间是:公元"+year+"年"+month+"月"+day+"日      "+hour+"时"+minute+"分"+second+"秒星期"+WeekOfYear);
                }

    待续。。。

  • 相关阅读:
    java
    EL表达式详解
    SVN的安装与配置
    javascript高级程序设计学习笔记
    java基础知识
    javascript高级程序设计学习笔记Chapter 5: Reference Types
    javascript模态,非模态窗体
    javascript执行顺序
    javascript的执行顺序2
    自动补全+汉字拼音双查(1)数据库
  • 原文地址:https://www.cnblogs.com/freemanabc/p/5493064.html
Copyright © 2011-2022 走看看