目录
6:SimpleDateFormat实现日期格式化与时间字符串解析
1:世界标准时间
public class DateTest {
// 标准时间 UTC GMT
// 1900-01-01 00:00:00
// 1970-01-01 00:00:00
@Test
public void test00(){
Date date = new Date();
long time = date.getTime();
long millis = System.currentTimeMillis();
// 1649933967034
System.out.println(time);
System.out.println(millis);
}
}
2:Date对象获取年份和与月份
public class DateTest {
@Test
public void test01() {
// 日期字符串
StringBuilder dateText = new StringBuilder();
// 获取日期对象
Date date = new Date();
// 年 月 日 时 分 秒 星期
int year = date.getYear() + 1900;
dateText.append(year + "年");
int month = date.getMonth() + 1;
dateText.append(month + "月");
int date1 = date.getDate();
System.out.println(dateText );
}
}
3:时间补零占位方法抽取
// 日期工具类
public abstract class BaseDateUtil {
/**
* 时间补零占位
* @param time 时间
* @return 是否补零
*/
public static String zeroCompensation(int time) {
if (time < 10) {
return "0" + time;
}
return String.valueOf(time);
}
}
4:对月份补零
public class DateTest {
@Test
public void test01() {
// 日期字符串
StringBuilder dateText = new StringBuilder();
// 获取日期对象
Date date = new Date();
// 年 月 日 时 分 秒 星期
int year = date.getYear() + 1900;
dateText.append(year + "年");
int month = date.getMonth() + 1;
dateText.append(BaseDateUtil.zeroCompensation(month) + "月");
int date1 = date.getDate();
System.out.println(dateText );
}
}
5:Date对象获取所有日期数据
public class DateTest {
// 标准时间 UTC GMT
// 1900-01-01 00:00:00
// 1970-01-01 00:00:00
@Test
public void test00() {
Date date = new Date();
long time = date.getTime();
long millis = System.currentTimeMillis();
// 1649933967034
System.out.println(time);
System.out.println(millis);
}
@Test
public void test01() {
// 日期字符串
StringBuilder dateText = new StringBuilder();
// 获取日期对象
Date date = new Date();
// 年 月 日 时 分 秒 星期
int year = date.getYear() + 1900;
dateText.append(year + "年");
int month = date.getMonth() + 1;
dateText.append(BaseDateUtil.zeroCompensation(month) + "月");
int dayOfMonth = date.getDate();
dateText.append(BaseDateUtil.zeroCompensation(dayOfMonth) + "日 ");
int hours = date.getHours();
dateText.append(BaseDateUtil.zeroCompensation(hours) + "时");
int minutes = date.getMinutes();
dateText.append(BaseDateUtil.zeroCompensation(minutes) + "分");
int seconds = date.getSeconds();
dateText.append(BaseDateUtil.zeroCompensation(hours) + "秒 ");
int dayOfWeek = date.getDay();
String weekDay = "星期";
switch (dayOfWeek){
case 1:{