进阶day01-DateFormat_字符串转换成Date对象的使用&练习

This commit is contained in:
2026-01-26 16:12:21 +08:00
parent c6129e50d1
commit 42120a0dbb
3 changed files with 72 additions and 2 deletions

View File

@@ -37,11 +37,11 @@ public class DateFormatDemo05 {
2019年3月16日 15时43分44秒
yyyy年MM月dd日 HH时mm分ss秒
*/
DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
// DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
/*
常用的方法:
- public String format(Date date)将Date对象格式化为字符串。
- public Date parse(String source)将字符串解析为Date对象。
*/
String formatDate = df.format(date);
System.out.println(formatDate);

View File

@@ -0,0 +1,31 @@
package com.inmind.date02;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
页面上用户直接输入一个时间字符串,但是我们后台又想获取该字符串的时间点,我们需要如何将
字符串转换成Date对象.
public Date parse(String source)将字符串解析为Date对象。
解析步骤:
1.创建日期格式化对象
2.定义一个时间字符串
3.调用解析方法
注意:在字符串解析成Date对象时,字母模式必须与时间的格式保持一致
*/
public class DateFormatDemo06 {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr = "2026-01-26 15:45:30";
//获取当前时间字符串的从基准时间到该时间点的毫秒值
//String----->Date
Date date = sdf.parse(dateStr);
System.out.println(date);
System.out.println(date.getTime());
}
}

View File

@@ -0,0 +1,39 @@
package com.inmind.date02;
import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
/*
8.练习:根据生日求出已经活了多少天
实现分析:
1.Scanner输入生日字符串
2.使用格式化的解析操作变成date对象
3.获取出生时的毫秒
4.获取当前系统的毫秒
5.求差,获取了咱们活了多少毫秒值
6.将毫秒值转换为天数
*/
public class Test07 {
public static void main(String[] args) throws ParseException {
//1.Scanner输入生日字符串
Scanner sc = new Scanner(System.in);
System.out.println("请输入您的生日例如1991-1-1");
String birStr = sc.nextLine();//生日字符串
//2.使用格式化的解析操作变成date对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date birDate = sdf.parse(birStr);
//3.获取出生时的毫秒
long beginTime = birDate.getTime();
//4.获取当前系统的毫秒
Date currentDate = new Date();
long currentDateTime = currentDate.getTime();
//5.求差,获取了咱们活了多少毫秒值
long liveTime = currentDateTime - beginTime;
//6.将毫秒值转换为天数
System.out.println("您已经生活的天数:"+(liveTime/24/60/60/1000));
}
}