Java 获取前3个小时整点时间字符串 - 代码示例
下面是一个使用Java编程语言获取包含当前时间的前3个小时整点字符串时间的示例代码:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Main {
public static void main(String[] args) {
// 获取当前系统时间
Calendar calendar = Calendar.getInstance();
Date currentTime = calendar.getTime();
// 将当前时间向前调整3个小时
calendar.add(Calendar.HOUR_OF_DAY, -3);
Date threeHoursBefore = calendar.getTime();
// 获取前3个小时整点时间
calendar.setTime(threeHoursBefore);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date threeHoursBeforeRounded = calendar.getTime();
// 格式化时间为字符串
SimpleDateFormat formatter = new SimpleDateFormat('yyyy-MM-dd HH:mm:ss');
String formattedTime = formatter.format(threeHoursBeforeRounded);
System.out.println('前3个小时整点时间:' + formattedTime);
}
}
运行以上代码会输出包含当前时间的前3个小时整点时间,格式为 'yyyy-MM-dd HH:mm:ss'。
原文地址: https://www.cveoy.top/t/topic/qwvB 著作权归作者所有。请勿转载和采集!