如果要设置日期和时间,请使用LocalDateTime 类。
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.concurrent.TimeUnit;
public class Example {
public static void main(String[] args) {
long hours = TimeUnit.MILLISECONDS.convert(18, TimeUnit.HOURS);
long minutes = TimeUnit.MILLISECONDS.convert(30, TimeUnit.MINUTES);
long seconds = TimeUnit.MILLISECONDS.convert(42, TimeUnit.SECONDS);
long time = hours + minutes + seconds; // 6:30:42 PM
Date date = toDate(2015, 10, 13, time);
DateFormat dateFmt = new SimpleDateFormat("MMM d yyyy hh:mm:ss a");
System.out.println(dateFmt.format(date)); // Oct 13 2015 06:30:42 PM
}
public static Date toDate(int year, int month, int date, long time) {
int hour = (int) TimeUnit.MILLISECONDS.toHours(time) % 24;
int minute = (int) TimeUnit.MILLISECONDS.toMinutes(time) % 60;
int second = (int) TimeUnit.MILLISECONDS.toSeconds(time) % 60;
int milli = (int) TimeUnit.MILLISECONDS.toMillis(time);
return toDate(year, month, date, hour, minute, second, milli);
}
public static Date toDate(int year, int month, int date) {
return toDate(year, month, date, 0);
}
public static Date toDate(int year, int month, int date, int hour) {
return toDate(year, month, date, hour, 0);
}
public static Date toDate(int year, int month, int date, int hour, int minute) {
return toDate(year, month, date, hour, minute, 0);
}
public static Date toDate(int year, int month, int date, int hour, int minute, int second) {
return toDate(year, month, date, hour, minute, second, 0);
}
public static Date toDate(int year, int month, int date, int hour, int minute, int second, int milli) {
return toDate(LocalDateTime.of(year, month, date, hour, minute, second, milli));
}
public static Date toDate(LocalDateTime timestamp) {
return Date.from(timestamp.atZone(ZoneId.systemDefault()).toInstant());
}
}