您的位置:首页 > 其它

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

2013-07-09 17:45 399 查看
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方法
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: