Date类型与格式字符串、毫秒的转化

1.JAVA日期加减运算2007-10-14 15:271.用java.util.Calender来实现

Calendar calendar=Calendar.getInstance();   
 calendar.setTime(new Date());
   System.out.println(calendar.get(Calendar.DAY_OF_MONTH));//今天的日期 
   calendar.set(Calendar.DAY_OF_MONTH,calendar.get(Calendar.DAY_OF_MONTH)+1);//让日期加1   
  System.out.println(calendar.get(Calendar.DATE));//加1之后的日期Top

2.用java.text.SimpleDateFormat和java.util.Date来实现

Date d=new Date();   
           SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");   
           System.out.println("今天的日期:"+df.format(d));   
           System.out.println("两天前的日期:" + df.format(new Date(d.getTime() - 2 * 24 * 60 * 60 * 1000)));   
           System.out.println("三天后的日期:" + df.format(new Date(d.getTime() + 3 * 24 * 60 * 60 * 1000))); 

注意SimpleDateFormat真正format的是Date数据

而将文本数据解析成日期对象 


import java.text.SimpleDateFormat; 
import java.util.Date;
 public class DateExample3
 {      public static void main(String[] args)
   {          // Create a date formatter that can parse dates of 
         // the form MM-dd-yyyy.
          SimpleDateFormat bartDateFormat = new SimpleDateFormat("MM-dd-yyyy");
          // Create a string containing a text date to be parsed. 
         String dateStringToParse = "9-29-2001";
          try {  
            // Parse the text version of the date.
              // We have to perform the parse method in a
              // try-catch construct in case dateStringToParse
              // does not contain a date in the format we are expecting. 
             Date date = bartDateFormat.parse(dateStringToParse); 
             // Now send the parsed date as a long value 
             // to the system output.
              System.out.println(date.getTime()); 
         }          
        catch (Exception ex) { 
             System.out.println(ex.getMessage()); 
         }     
    }
 }

Date对象实质上是一个日期转化成的毫秒数

1.
日期类型转化为毫秒数
Date d = new Date();
long m = d.getTime();
毫秒数转日期类型
Date dd = new Date(m) ;//通过毫秒数构造Date对象

2.
把年月日格式字符串转化为Date类型 ,用的是SimpleDateFormat对象的parse方法

把Date类型转化为年月日格式字符串类型,用的是SimpleDateFormat对象的format方法


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值