获取时间戳(自1970年1月1日经历的毫秒数值)
package org.example;
import java.util.Date;
public class Main {
public static void main(String[] args) {
Date date1 = new Date(1699540662210L);
System.out.println(date1.getTime());
Date date2= new Date();
System.out.println(date2.getTime());
}
}
输出时间的毫秒数:
1699540662210
1699540757409
时间戳格式化
package org.example;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Main {
public static void main(String[] args) throws ParseException {
// 定义输出格式
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// 将字符串转化为日期
Date date = sdf.parse("2023-11-09 22:43:17");
System.out.println(date.getTime()); // 1699540997000
Date date1 = new Date();
// 将日期转化为字符串
SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str = sdf1.format(date1);
System.out.println(str); // 2023-11-09 22:44:46
}
}
从字符串解析成Date对象,用到了parse方法。
从Date对象格式化成字符串,用到format方法。SimpleDateFormat
构造方法是日期格式。
获取年月日
package org.example;
import java.util.Calendar;
public class Main {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
// 年
int year = calendar.get(Calendar.YEAR);
System.out.println(year);
// 月
int month = calendar.get(Calendar.MONTH) + 1 ;
// 在Calendar类中,月份的表示是以0-11代表1-12月(可以+1使用)。
System.out.println(month);
// 日
int dayOfMonth = calendar.get(Calendar.DAY_OF_MONTH);
System.out.println(dayOfMonth);
// 周几
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;
// 西方星期的开始为周日(1)周一(2),中国开始为周一,因此可以-1使用。
System.out.println(dayOfWeek);
// 加一天
calendar.add(Calendar.DAY_OF_MONTH, 7);
System.out.println(calendar.get(Calendar.WEEK_OF_MONTH));
}
}
这里用Calendar来获取年月日。