gpt4 book ai didi

Java将毫秒添加到毫秒时间戳省略周末和节假日

转载 作者:行者123 更新时间:2023-11-30 08:00:28 26 4
gpt4 key购买 nike

我是初学者,我想将毫秒添加到 java 时间戳(以毫秒为单位)并获取以毫秒为单位的结果时间以进行进一步操作。我曾尝试通过每毫秒增加时间戳并检查它是否到达假期或周末来做到这一点,然后我跳过那一天。这样做不太明智。需要永远。有人已经发明了轮子吗?

这是我糟糕且非常糟糕的代码(不要使用这个,需要很长时间)

public static class businessdays {

public static long addWorkingTime(long timestamp, long milliseconds){

for (int i=0;i<milliseconds;i ++){
long test_timestamp = timestamp + 1;
while (isHoliday(test_timestamp)){
System.out.println("isHoliady");
timestamp += 24 * 60 * 60 * 1000; //jump weekend or holiday
test_timestamp += (12 * 60 * 60 * 1000);
}
timestamp += i;
}

return timestamp;
}

private static boolean isHoliday(long timestamp){
List<String> holidays = new ArrayList<String>(Arrays.asList("01/01,05/01,06/01,10/20,12/12,12/25,12/26".split(",")));
SimpleDateFormat dw = new SimpleDateFormat("u"); //date of the week - 1 - 7
SimpleDateFormat dd = new SimpleDateFormat("dd"); //1 - 30/31
SimpleDateFormat dm = new SimpleDateFormat("MM"); //1 - 12
Date test_timeDate = new Date(timestamp);
String date = dm.format(test_timeDate)+"/"+dd.format(test_timeDate); //MM/dd
String doweek = dw.format(test_timeDate);
if (holidays.contains(date) || doweek.contains("6") || doweek.contains("7")){
return true;
}
return false;
}
}

最佳答案

日历类可以让您在几天内进行操作,这可能会更可取。对于日期处理来说,毫秒往往是一个幼稚的选择,因为并非所有日期都有相同的毫秒数。每隔一段时间就会插​​入闰秒,夏令时的每一天都会比通常的 24 小时少或多一小时。

final static int DAY_MILLIS = 24 * 60 * 60 * 1000;
static String hols[] = new String[] { "01/01", "05/01", "06/01", "10/20", "12/12", "12/25", "12/26" };

public static long addWorkingTime(long timestamp, long milliseconds)
{
// Get a calendar from a timestamp.
Calendar cal = new GregorianCalendar();
cal.setTimeInMillis(timestamp);
while (isHoliday(cal)) cal.add(Calendar.DATE, 1);

// Count off the days in milliseconds.
int days = (int)(milliseconds / DAY_MILLIS);
for (int i = 0; i < days; i++) {
cal.add(Calendar.DATE, 1);
while (isHoliday(cal)) cal.add(Calendar.DATE, 1);
}

// Apply the leftover from milliseconds if there is any.
milliseconds = milliseconds - days * DAY_MILLIS;
cal.add(Calendar.MILLISECOND, milliseconds);
while (isHoliday(cal)) cal.add(Calendar.DATE, 1);

// Return a timestamp from a calendar.
return cal.getTimeInMillis();
}

static boolean isHoliday(Calendar cal)
{
int dow = cal.get(Calendar.DAY_OF_WEEK);
if (dow == Calendar.SATURDAY || dow == Calendar.SUNDAY) return true;
String mmdd = new SimpleDateFormat("MM/dd").format(cal.getTime());
return Arrays.binarySearch(hols, mmdd) >= 0;
}

关于Java将毫秒添加到毫秒时间戳省略周末和节假日,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022804/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com