美文网首页
Android日期处理

Android日期处理

作者: sylcrq | 来源:发表于2016-10-24 14:48 被阅读69次

    1.计算两个日期之间相差的天数

    Java, Calculate the number of days between two dates

    // http://en.wikipedia.org/wiki/Julian_day
    public static int julianDay(int year, int month, int day) {
     int a = (14 - month) / 12;
     int y = year + 4800 - a;
     int m = month + 12 * a - 3;
     int jdn = day + (153 * m + 2)/5 + 365*y + y/4 - y/100 + y/400 - 32045;
     return jdn;
    }
    public static int diff(int y1, int m1, int d1, int y2, int m2, int d2) {
     return julianDay(y1, m1, d1) - julianDay(y2, m2, d2);
    }
    

    2.获取当前日期

    How to get the current date/time in java

    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Date date = new Date();
    System.out.println(dateFormat.format(date)); //2014/08/06 15:59:48
    
    DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    System.out.println(dateFormat.format(cal.getTime())); //2014/08/06 16:00:22
    

    3.获取当前年/月/日等信息

    How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

    Calendar now = Calendar.getInstance();
    int year = now.get(Calendar.YEAR);
    int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
    int day = now.get(Calendar.DAY_OF_MONTH);
    int hour = now.get(Calendar.HOUR_OF_DAY);
    int minute = now.get(Calendar.MINUTE);
    int second = now.get(Calendar.SECOND);
    int millis = now.get(Calendar.MILLISECOND);
    System.out.printf("%d-%02d-%02d %02d:%02d:%02d.%03d", year, month, day, hour, minute, second, millis);
    

    相关文章

      网友评论

          本文标题:Android日期处理

          本文链接:https://www.haomeiwen.com/subject/kidluttx.html