Date类
Date类中许多方法已经过时,总结几个常用的方法。
1.Date类的setTime()和getTime()方法
getTime
public long getTime()
- 返回自 1970 年 1 月 1 日 00:00:00 GMT 以来此 Date 对象表示的毫秒数。
- 返回:
- 自 1970 年 1 月 1 日 00:00:00 GMT 以来此日期表示的毫秒数。
setTime
public void setTime(long time)
- 设置此
Date
对象,以表示 1970 年 1 月 1 日 00:00:00 GMT 以后time
毫秒的时间点。 - 参数:
time
- 毫秒数。
示例:
1 package cmd.Data; 2 3 import java.text.SimpleDateFormat; 4 import java.util.Date; 5 6 public class Demo1 { 7 public static void main(String args[]){ 8 Date time = new Date(); 9 System.out.println(time); 10 time.setTime(time.getTime() + 24 * 3600 * 1000); 11 SimpleDateFormat sdt = new SimpleDateFormat("yyyy年-MM月-dd日 HH:mm:ss"); 12 System.out.println(sdt.format(time)); 13 } 14 }
Tue Jul 04 21:52:25 CST 2017
2017年-07月-05日 21:52:25
在当前时间加上一天的毫秒数并输出
2.
SimpleDateFormat类
parse()方法
parse
public Date parse(String text, ParsePosition pos)
- 解析字符串的文本,生成
Date
。此方法试图解析从
pos
给定的索引处开始的文本。如果解析成功,则将pos
的索引更新为所用最后一个字符后面的索引(不必对直到字符串结尾的所有字符进行解析),并返回解析得到的日期。更新后的pos
可以用来指示下次调用此方法的起始点。如果发生错误,则不更改pos
的索引,并将pos
的错误索引设置为发生错误处的字符索引,并且返回 null。 - 指定者:
- 类
DateFormat
中的parse
- 参数:
text
- 应该解析其中一部分的String
。pos
- 具有以上所述的索引和错误索引信息的ParsePosition
对象。- 返回:
- 从字符串进行解析的
Date
。如果发生错误,则返回 null。 - 抛出:
NullPointerException
- 如果text
或pos
为 null。
示例:
1 package cmd.Data; 2 3 import java.text.ParseException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 public class Demo2 { 8 public static void main(String args[]) throws ParseException{ 9 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 10 Date birthDay = sdf.parse("1997-07-13"); 11 birthDay.setTime(birthDay.getTime() + (long)1000 * 3600 * 24 * 10000); 12 System.out.println(sdf.format(birthDay)); 13 } 14 }
2024-11-28
将输入的String格式的时间解析成Date对象,在进行运算转换格式输出
date->String
String->Date