时间格式总结(java)

String转date==> parse
Calendar转StringBuffer==>format
date和Calendar互转==>setTime()转Calendar==>getTime转date

(如:calendar.setTime(new Date()) calendar.getTime())
首先下面是代码,想要的伙伴可以直接拿
/**
* 获取本月第一天的日期
*

 */
 public static String RecentlyMonth() {
    SimpleDateFormat format1 = new SimpleDateFormat("yyyyMMdd");
    //实例化时间
    Calendar cale = Calendar.getInstance();
    System.out.println(format1.format(cale.getTime()));//此时输出20200515
    cale.set(Calendar.DAY_OF_MONTH, 1);
    return format1.format(cale.getTime());//返回20200501
}

/**
 * 获取本周第一天的日期
 *
 * @return
 */
public static String RecentlyWeek() {

    SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

    Calendar cale = Calendar.getInstance();
    //老外第一天是星期天所以我们要获取他的第二天
    cale.set(Calendar.DAY_OF_WEEK, 2);
    return format.format(cale.getTime());
}


//输入一个过去时间推进x天和今天比较大小
    public static boolean judge(String str, Integer timetableRDay) {

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date da = null;
    try {
        da = sdf.parse(str);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    System.out.println(da);
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(da);
    calendar.add(Calendar.DATE, timetableRDay - 1);
    Date date = calendar.getTime();

    System.out.println(new Date());
    if (date.before(new Date())) {
        //表示bt小于et
        return false;
    }
    return true;

}
/**
 * 获取昨天的时间
 *
 * @return
 */
public static String RecentlyYesterday() {
    // 获取昨日的日期
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -1);
    return sdf.format(c.getTime());
}

/**
 * 往前推n天(日期)
 */
public static String RecentlyNDay(int n) {
    // 获取n天以前的日期
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Calendar c = Calendar.getInstance();
    c.add(Calendar.DATE, -n);
    return sdf.format(c.getTime());
}

/**
 * 指定時間往前推一天
 *
 * @return
 */
public static String BeforeDay(String date) {
    //(注意输入的格式要和sdf格式一致)
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Date da = null;
    try {
        da = sdf.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar c = Calendar.getInstance();
    c.setTime(da);
    c.add(Calendar.DATE, -1);
    return sdf.format(c.getTime());
}

/**
 * 获取今天是本周第几天
 */
public static int day() {
    Calendar c = Calendar.getInstance();
    return c.get(Calendar.DAY_OF_WEEK) - 1;//当输出7是星期六,我一般认为他是第六天
}

/**
 * 获取今天是本月第几周
 */
public static int week() {
    Calendar c = Calendar.getInstance();
    return c.get(Calendar.WEEK_OF_MONTH);
}

/**
 * 获取提供时间前n周的日期
 */
public static String weekN(String date, int n) {
    // 获取n周以前的日期
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    Date da = null;
    try {
        da = sdf.parse(date);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    Calendar c = Calendar.getInstance();
    c.setTime(da);
    c.add(Calendar.WEEK_OF_MONTH, -n);
    return sdf.format(c.getTime());
}

日期格式

date格式:

当前年份:(Java中的Date表示的是自1900年以来所经过的时间。所以要得到真实年份的话需要加上1900.)

d.getYear()+1900

当前月份

d.getMonth()+1

当前几号

d.getDate()

当前星期几

d.getDay()20190903星期2

当前小时分钟秒

System.out.println(d.getHours());
System.out.println(d.getMinutes());
System.out.println(d.getSeconds());
Date d = new Date();
System.out.println((d.getYear()+1900)+"年"+         (d.getMonth()+1)+"月"+d.getDate()+"号"+d.getHours()+"时"+d.getMinutes()+"分"+d.getSeconds()+"秒"+",今天是星期"+d.getDay());
console:201993113843,今天是星期2

当前时间戳

d.getTime()    (注意是毫秒)
自己定义的时间时他会自动处理大于11的月份
/**
     * Allocates a <code>Date</code> object and initializes it so that
     * it represents the instant at the start of the second specified
     * by the <code>year</code>, <code>month</code>, <code>date</code>,
     * <code>hrs</code>, <code>min</code>, and <code>sec</code> arguments,
     * in the local time zone.
     *
     * @param   year    the year minus 1900.
     * @param   month   the month between 0-11.
     * @param   date    the day of the month between 1-31.
     * @param   hrs     the hours between 0-23.
     * @param   min     the minutes between 0-59.
     * @param   sec     the seconds between 0-59.
     * @see     java.util.Calendar
     * @deprecated As of JDK version 1.1,
     * replaced by <code>Calendar.set(year + 1900, month, date,
     * hrs, min, sec)</code> or <code>GregorianCalendar(year + 1900,
     * month, date, hrs, min, sec)</code>.
     */
    @Deprecated
    public Date(int year, int month, int date, int hrs, int min, int sec) {
        int y = year + 1900;
        // month is 0-based. So we have to normalize month to support Long.MAX_VALUE.
        if (month >= 12) {
            y += month / 12;
            month %= 12;
        } else if (month < 0) {
            y += CalendarUtils.floorDivide(month, 12);
            month = CalendarUtils.mod(month, 12);
        }
        BaseCalendar cal = getCalendarSystem(y);
        cdate = (BaseCalendar.Date) cal.newCalendarDate(TimeZone.getDefaultRef());
        cdate.setNormalizedDate(y, month + 1, date).setTimeOfDay(hrs, min, sec, 0);
        getTimeImpl();
        cdate = null;
    }
```### calendar格式

```java
 /**
     * Gets a calendar using the default time zone and locale. The
     * <code>Calendar</code> returned is based on the current time
     * in the default time zone with the default
     * {@link Locale.Category#FORMAT FORMAT} locale.
     *
     * @return a Calendar.
     */
    public static Calendar getInstance()
    {
        return createCalendar(TimeZone.getDefault(), Locale.getDefault(Locale.Category.FORMAT));
    }


calendar为抽象类不能直接构造方法实例化,一般使用getInstance去实例化

SimpleDateFormat实例化(有待深入理解)

设置年月日:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = sdf.getCalendar();
		cal.set(2019, 9-1,3);
		System.out.println(sdf.format(cal.getTime()));
console:20190903

不做任何设置

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = sdf.getCalendar();
//		cal.set(Calendar.YEAR,2019);
		System.out.println(sdf.format(cal.getTime()));
console:19390903 (时间戳转换为1970-01-01 13:23:10,为当前时间-80)注意这个实例化方式还待深入
用日期自己的实例化:
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.YEAR,2019);
		cal.set(Calendar.MONDAY,2-1);
		cal.set(Calendar.DATE,2);
		System.out.println(sdf.format(cal.getTime()));
console:20190202  (用日期格式是不需要再减去1970的但是月份还是从0开始)
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		Calendar cal = Calendar.getInstance();
//		cal.set(Calendar.YEAR,2019);
//		cal.set(Calendar.MONDAY,2-1);
//		cal.set(Calendar.DATE,2);
		System.out.println(sdf.format(cal.getTime()));
console:20190903 (默认就是当前时间)
   SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar cal = Calendar.getInstance();
        //获取当前年份
        int year = cal.get(Calendar.YEAR);
        //获取当前月份
        int month = cal.get(Calendar.MONTH);
        //获取当前年份
        int date = cal.get(Calendar.DAY_OF_MONTH);
        //获取当前是一个星期几
        int day = cal.get(Calendar.DAY_OF_WEEK);
        //获取当前是第几小时(24小时制)
        int hour = cal.get(Calendar.HOUR_OF_DAY);
        //获取当前是第几小时(12小时制)
        int hour2 = cal.get(Calendar.HOUR);
        //获取当前分钟
        int minute = cal.get(Calendar.MINUTE);
        System.out.println("year: " + (year));
        System.out.println("month: " + (month+1));
        System.out.println("date: " + (date));
        System.out.println("day: " + (day - 1));
        System.out.println("hour: " + hour);
        System.out.println("hour2: " + hour2);
        System.out.println("minute: " + minute);
console:
year: 2019
month: 9
date: 3
day: 2
hour: 15
hour2: 3
minute: 28
minute: 18  (注意老外的月份是从0开始,星期天是一个星期的第一天)
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Calendar cal = Calendar.getInstance();

        cal.add(Calendar.YEAR,-1);
        System.out.println(sdf.format(cal.getTime()));
console:20180903 (年份-1
date和calendar格式:
date:
	Tue Sep 03 16:20:13 CST 2019
calendar: (时间戳:15674988136422019-09-03 16:20:13)  java.util.GregorianCalendar[time=1567498813642,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Shanghai",offset=28800000,dstSavings=0,useDaylight=false,transitions=19,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2019,MONTH=8,WEEK_OF_YEAR=36,WEEK_OF_MONTH=1,DAY_OF_MONTH=3,DAY_OF_YEAR=246,DAY_OF_WEEK=3,DAY_OF_WEEK_IN_MONTH=1,AM_PM=1,HOUR=4,HOUR_OF_DAY=16,MINUTE=20,SECOND=13,MILLISECOND=642,ZONE_OFFSET=28800000,DST_OFFSET=0]

date类型现在几乎不使用了,在其源码也可看到很多方法都加上了 @Deprecated,
下面详细说下Calendar格式;
在Calendar格式中年份不在需要减去1900, 老外的观念中月份是从0开始的所以别忘了转为中国月份+1,老外一个星期的第一天是星期天,如果你也是这种观念不必(当前本周第几天)-1,Calendar中有获取当前周是本月第几周的方法,WEEOFMONTH,今天是本周第几天的方法DAYOFWEEK,今年第几月MONTHOFYEAR

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值