Android 获取当前时间(时间比较是否是今天)

35 篇文章 0 订阅

不废话上代码

/**
 * Copyright:hongyu
 * Created by Baron on 2020/9/18 5:20 PM
 * Emaile:wanghongyuwh@163.com
 * Description:
 * Modify time:
 * Modified by:
 */
public class DateUtil {
    public static final int SECONDS_IN_DAY = 60 * 60 * 24;
    public static final long MILLIS_IN_DAY = 1000L * SECONDS_IN_DAY;

    public static boolean isSameDayOfMillis(final long ms1, final long ms2) {
        final long interval = ms1 - ms2;
        return interval < MILLIS_IN_DAY
                && interval > -1L * MILLIS_IN_DAY
                && toDay(ms1) == toDay(ms2);
    }

    private static long toDay(long millis) {
        return (millis + TimeZone.getDefault().getOffset(millis)) / MILLIS_IN_DAY;
    }

    /**
     * 获取UTC+0的时区时间
     *
     * @param timeMillisl
     * @return
     */
    public static String formatTimeYMDByUTC00(long timeMillisl) {
        SimpleDateFormat d_f = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式
        d_f.setTimeZone(TimeZone.getTimeZone("UTC+00"));
        return d_f.format(new Date(timeMillisl));
    }

    public static String formatTime(long timeMillisl) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(timeMillisl);
        return simpleDateFormat.format(date);
    }

    //毫秒换成00:00:00
    public static String getCountTimeByLong(long finishTime) {
        int totalTime = (int) (finishTime / 1000);//秒
        int hour = 0, minute = 0, second = 0;

        if (3600 <= totalTime) {
            hour = totalTime / 3600;
            totalTime = totalTime - 3600 * hour;
        }
        if (60 <= totalTime) {
            minute = totalTime / 60;
            totalTime = totalTime - 60 * minute;
        }
        if (0 <= totalTime) {
            second = totalTime;
        }
        StringBuilder sb = new StringBuilder();

//		if (hour < 10) {
//			sb.append("0").append(hour).append(":");
//		} else {
//			sb.append(hour).append(":");
//		}
        if (minute < 10) {
            sb.append("0").append(minute).append(":");
        } else {
            sb.append(minute).append(":");
        }
        if (second < 10) {
            sb.append("0").append(second);
        } else {
            sb.append(second);
        }
        return sb.toString();

    }

    public static String[] weekName = {"周日", "周一", "周二", "周三", "周四", "周五",
            "周六"};

    public static int getMonthDays(int year, int month) {
        if (month > 12) {
            month = 1;
            year += 1;
        } else if (month < 1) {
            month = 12;
            year -= 1;
        }
        int[] arr = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        int days = 0;

        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            arr[1] = 29;
        }

        try {
            days = arr[month - 1];
        } catch (Exception e) {
            e.getStackTrace();
        }

        return days;
    }

    public static int getYear() {
        return Calendar.getInstance().get(Calendar.YEAR);
    }

    public static int getMonth() {
        return Calendar.getInstance().get(Calendar.MONTH) + 1;
    }

    public static int getCurrentMonthDay() {
        return Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
    }

    public static int getWeekDay() {
        return Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
    }

    public static int getHour() {
        return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    }

    public static int getMinute() {
        return Calendar.getInstance().get(Calendar.MINUTE);
    }

    public static int[] getWeekSunday(int year, int month, int day, int pervious) {
        int[] time = new int[3];
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, day);
        c.add(Calendar.DAY_OF_MONTH, pervious);
        time[0] = c.get(Calendar.YEAR);
        time[1] = c.get(Calendar.MONTH) + 1;
        time[2] = c.get(Calendar.DAY_OF_MONTH);
        return time;

    }

    public static int getWeekDayFromDate(int year, int month) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(getDateFromString(year, month));
        int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (week_index < 0) {
            week_index = 0;
        }
        return week_index;
    }

    @SuppressLint("SimpleDateFormat")
    public static Date getDateFromString(int year, int month) {
        String dateString = year + "-" + (month > 9 ? month : ("0" + month))
                + "-01";
        Date date = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            System.out.println(e.getMessage());
        }
        return date;
    }

    public static String timeFormat1 = "MM-dd HH:mm"; // 03-20 3:10

    /**
     * @param time
     * @return
     */
    public static String getCurrentTime(String time) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            return formatter.format(calendar.getTime());
        } catch (Exception e) {
        }
        return "";
    }

    public static long getChronometerBaseTime(String string) {
        try {
            return (Long.parseLong(string.split(":")[0]) * 60 + Long
                    .parseLong(string.split(":")[1])) * 1000;
        } catch (Exception e) {
        }
        return 0;
    }

    // /**
    // * @param args
    // * @throws java.text.ParseException
    // * @throws ParseException
    // */
    // public static void main(String[] args) throws ParseException,
    // java.text.ParseException {
    // DateUtil du = new DateUtil();
    // // String s = du.numToDate(1350144260, "yyyy-MM-dd hh:mm:ss");
    // long time = du
    // .stringToLong("2012-10-15 8:44:53", "yyyy-MM-dd hh:mm:ss") / 1000;
    // long time1 = du.stringToLong("2012-10-15 20:44:53",
    // "yyyy-MM-dd hh:mm:ss") / 1000;
    // String date = du.longToString(1350470693, "yyyy-MM-dd hh:mm:ss");
    // System.out.println(time);
    // System.out.println(time1);
    // System.out.println(date);
    //
    // }

    // date类型转换为String类型
    // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    // data Date类型的时间
    public static String dateToString(Date data, String formatType) {
        return new SimpleDateFormat(formatType).format(data);
    }

    // long类型转换为String类型
    // currentTime要转换的long类型的时间
    // formatType要转换的string类型的时间格式
    public static String longToString(long currentTime, String formatType)
            throws ParseException, ParseException {
        Date date = longToDate(currentTime, formatType); // long类型转成Date类型
        String strTime = dateToString(date, formatType); // date类型转成String
        return strTime;
    }

    // string类型转换为date类型
    // strTime要转换的string类型的时间,formatType要转换的格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日
    // HH时mm分ss秒,
    // strTime的时间格式必须要与formatType的时间格式相同
    public static Date stringToDate(String strTime, String formatType)
            throws ParseException, ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }

    // long转换为Date类型
    // currentTime要转换的long类型的时间
    // formatType要转换的时间格式yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒
    public static Date longToDate(long currentTime, String formatType)
            throws ParseException, ParseException {
        Date dateOld = new Date(currentTime); // 根据long类型的毫秒数生命一个date类型的时间
        String sDateTime = dateToString(dateOld, formatType); // 把date类型的时间转换为string
        Date date = stringToDate(sDateTime, formatType); // 把String类型转换为Date类型
        return date;
    }

    // string类型转换为long类型
    // strTime要转换的String类型的时间
    // formatType时间格式
    // strTime的时间格式和formatType的时间格式必须相同
    public static long stringToLong(String strTime, String formatType)
            throws ParseException, ParseException {
        Date date = stringToDate(strTime, formatType); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = dateToLong(date); // date类型转成long类型
            return currentTime;
        }
    }

    // date类型转换为long类型
    // date要转换的date类型的时间
    public static long dateToLong(Date date) {
        return date.getTime();
    }

    public static String numToDate(int number, String formatType) {
        Date date = new Date(number);
        SimpleDateFormat sdf = new SimpleDateFormat(formatType);
        return sdf.format(date);
    }


    private final static long minute = 60 * 1000;// 1分钟
    private final static long hour = 60 * minute;// 1小时
    private final static long day = 24 * hour;// 1天
    private final static long month = 31 * day;// 月
    private final static long year = 12 * month;// 年



    public static long getLongTime(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return format.parse(time).getTime();
        } catch (ParseException e) {
        }

        return 0L;
    }


    // 这个时间戳是不是今天
    public static boolean isTodayTimeByTime(long oldTime) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String d1 = format.format(new Date(oldTime));
        Date nowdate = new Date();
        String d2 = format.format(nowdate);
        if (d1.equalsIgnoreCase(d2)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     *
     * @return
     */
    public static long currentTimeMillis() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            return simpleDateFormat.parse(DateFormat.format("yyyy-MM-dd HH:mm:ss", calendar).toString()).getTime();
        } catch (ParseException e) {
        }
        return System.currentTimeMillis();
    }
}

//首先判断是否是今天那肯定是要判断当前时间举个例子现在有好多app有一些浮窗入口那么有些用户会点击叉号不想看到浮窗但是用户点击浮窗后今天就不可以再次显示了因为这样会很影响用户的体验所以要判断是否是当天,在点击叉号的同时需要记住当前点击的时间,来进行会服务端的开始时间与结束时间进行对比来决定浮窗是进行显示。

//当前时间转换。。这个只是但前时间 如果后台给了开始时间与结束时间转换方式同下

  long currentTime = System.currentTimeMillis();
 //当前时间
  present = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentTime);
  //如果需要进行比较时间的话
  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  Date start_time = dateFormat.parse(starttime);
  //接下来就是个根据逻辑if判断时间了与接口的开始时间与结束时间进行比较转换格式同上

注意 时间一般是long类型所以大多需要进行转换

最后感谢观看欢迎转发

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王富贵王富贵王富贵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值