package com.lightinit.hsdataplatformresdir.common;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Created by Mr.Yao on 2017/9/26.
 */
public class DateUtils {
    public static int daysBetween(String begindate, String enddate) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(sdf.parse(begindate));
            long time1 = cal.getTimeInMillis();
            cal.setTime(sdf.parse(enddate));
            long time2 = cal.getTimeInMillis();
            long between_days = (time2 - time1) / (1000 * 3600 * 24);

            return Integer.parseInt(String.valueOf(between_days));
        } catch (ParseException e) {
            return 0;
        }
    }

    public static String weekBeginDate(Date date) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int d = 0;
            if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
                d = -6;
            } else {
                d = 2 - cal.get(Calendar.DAY_OF_WEEK);
            }
            cal.add(Calendar.DAY_OF_WEEK, d);
            return simpleDateFormat.format(cal.getTime());
        } catch (Exception e) {
            return "";
        }
    }

    public static String weekEndDate(Date date) {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);
            int d = 0;
            if (cal.get(Calendar.DAY_OF_WEEK) == 1) {
                d = -6;
            } else {
                d = 2 - cal.get(Calendar.DAY_OF_WEEK);
            }
            cal.add(Calendar.DAY_OF_WEEK, d);
            cal.add(Calendar.DAY_OF_WEEK, 6);
            return simpleDateFormat.format(cal.getTime());
        } catch (Exception e) {
            return "";
        }
    }

    public static Date StringToDate(String str) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date result = sdf.parse(str);
            return result;
        } catch (ParseException ex) {
            return null;
        }
    }

    public static int YearOfDate() {
        Calendar now = Calendar.getInstance();
        return now.get(Calendar.YEAR);
    }

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