java中日期时间格式与毫秒数的转换如何将指定时间转换为Date类型

来源:互联网 发布:怎样参加淘宝活动 编辑:程序博客网 时间:2024/05/01 14:22

[html] view plain copy
  1. //输入日期转化为毫秒数 ---用calendar方法(calendar.getTime)  
  2.         Calendar calendar = Calendar.getInstance();  
  3.         calendar.set(2018, 2, 15, 8, 31, 5);  
  4.         System.out.println(calendar.getTimeInMillis());  


[html] view plain copy
  1. //输入日期,转化为毫秒数,用DATE方法()  
  2.         /**  
  3.          * 先用SimpleDateFormat.parse() 方法将日期字符串转化为Date格式  
  4.          * 通过Date.getTime()方法,将其转化为毫秒数  
  5.          */  
  6.         String date = "2001-03-15 15-37-05";  
  7.         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//24小时制  
  8. //      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");//12小时制  
  9.         long time2 = simpleDateFormat.parse(date).getTime();  
  10.         System.out.println(time2);  


[html] view plain copy
  1. //输入毫秒数,转化为日期,用simpleDateFormat  +  Date 方法;  
  2.         /**  
  3.          * 直接用SimpleDateFormat格式化 Date对象,即可得到相应格式的日期 字符串。  
  4.          */  
  5.         long time3 = System.currentTimeMillis() + 5000 *1000;  
  6.           
  7.         Date date2 = new Date();  
  8.         date2.setTime(time3);  
  9.         System.out.println(simpleDateFormat.format(date2));  


[html] view plain copy
  1. //输入毫秒数,转化为日期,用calendar方法;  
  2.         Calendar calendar2 = Calendar.getInstance();  
  3.         calendar2.setTimeInMillis(time3);  
  4.         int year = calendar2.get(Calendar.YEAR);  
  5.         int month = calendar2.get(Calendar.MONTH);  
  6.         int day = calendar2.get(Calendar.DAY_OF_MONTH);  
  7.         int hour = calendar2.get(Calendar.HOUR_OF_DAY);//24小时制  
  8. //      int hour = calendar2.get(Calendar.HOUR);//12小时制  
  9.         int minute = calendar2.get(Calendar.MINUTE);  
  10.         int second = calendar2.get(Calendar.SECOND);  
  11.           
  12.         System.out.println(year + "年" + (month + 1) + "月" + day + "日"  
  13.                 + hour + "时" + minute + "分" + second + "秒");  
将指定时间转换为Date类型:

String date = "2001-03-15 15-37-05";
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
long time2 = simpleDateFormat.parse(date).getTime();
System.out.println(time2);


0 0
原创粉丝点击