Java判斷某時間是否在一個時間段__java

來源:互聯網
上載者:User
import Java.text.ParseException; import java.text.SimpleDateFormat;public class DateTest {/** * @param args */public static void main(String[] args) {    System.out.println(DateTest.isInTime("20:00-01:00", "01:00"));    System.out.println(DateTest.isInTime("20:00-01:00", "00:00"));    System.out.println(DateTest.isInTime("20:00-01:00", "03:00"));    System.out.println();    System.out.println(DateTest.isInTime("20:00-23:00", "03:00"));    System.out.println(DateTest.isInTime("20:00-23:00", "22:00"));    System.out.println(DateTest.isInTime("20:00-23:00", "18:00"));    System.out.println(DateTest.isInTime("20:00-23:00", "20:00"));    System.out.println(DateTest.isInTime("20:00-23:00", "23:00"));}/** * 判斷某一時間是否在一個區間內 *  * @param sourceTime *            時間區間,半閉合,如[10:00-20:00) * @param curTime *            需要判斷的時間 如10:00 * @return  * @throws IllegalArgumentException */public static boolean isInTime(String sourceTime, String curTime) {    if (sourceTime == null || !sourceTime.contains("-") || !sourceTime.contains(":")) {        throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);    }    if (curTime == null || !curTime.contains(":")) {        throw new IllegalArgumentException("Illegal Argument arg:" + curTime);    }    String[] args = sourceTime.split("-");    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");    try {        long now = sdf.parse(curTime).getTime();        long start = sdf.parse(args[0]).getTime();        long end = sdf.parse(args[1]).getTime();        if (args[1].equals("00:00")) {            args[1] = "24:00";        }        if (end < start) {            if (now >= end && now < start) {                return false;            } else {                return true;            }        }         else {            if (now >= start && now < end) {                return true;            } else {                return false;            }        }    } catch (ParseException e) {        e.printStackTrace();        throw new IllegalArgumentException("Illegal Argument arg:" + sourceTime);    }}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.