使用System.currentTimeMillis()方法
System.currentTimeMillis()方法返回當(dāng)前時間的時間戳,以毫秒為單位。我們可以通過除以1000來將其轉(zhuǎn)換為秒。
long timestamp = System.currentTimeMillis() / 1000;
使用Calendar類
Java提供了Calendar類來處理日期和時間。我們可以通過獲取Calendar實例,并使用get方法獲取當(dāng)前的年、月、日。
import java.util.Calendar; Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH) + 1; int day = calendar.get(Calendar.DAY_OF_MONTH);
使用SimpleDateFormat類
SimpleDateFormat類是Java中處理日期和時間格式化的常用類。我們可以使用它來獲取當(dāng)前日期的字符串表示,并將其轉(zhuǎn)換為時間戳。
import java.text.SimpleDateFormat;
import java.util.Date;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String currentDate = sdf.format(new Date());
long timestamp = sdf.parse(currentDate).getTime() / 1000;使用Java 8的LocalDate類
Java 8引入了新的日期和時間API。我們可以使用LocalDate類來獲取當(dāng)前的年、月、日,并使用toEpochDay方法將其轉(zhuǎn)換為時間戳。
import java.time.LocalDate; LocalDate currentDate = LocalDate.now(); long timestamp = currentDate.toEpochDay() * 24 * 60 * 60;
使用Joda-Time庫
Joda-Time是一個廣受歡迎的Java日期和時間處理庫。我們可以使用它來獲取當(dāng)前的年、月、日,并使用toDateTime方法將其轉(zhuǎn)換為時間戳。
import org.joda.time.DateTime; DateTime currentDate = new DateTime(); long timestamp = currentDate.toDateTime().getMillis() / 1000;
總結(jié)
本文介紹了在Java中獲取當(dāng)前年月日的時間戳的幾種方法,包括使用System.currentTimeMillis()方法、Calendar類、SimpleDateFormat類、Java 8的LocalDate類和Joda-Time庫。根據(jù)具體需求和使用場景,選擇適合的方法來獲取當(dāng)前時間的時間戳。