Java 类java.util.Calendar 实例源码

项目:CommonFramework    文件:DateUtilsTest.java   
@Test
public void sameDate() throws Exception {
    String format = "yyyyMMddHHmm";
    Calendar calendar = Calendar.getInstance();
    // 月份从0开始: 2017-04-20 15:50
    calendar.set(2017, 03, 20, 15, 50);
    Date date1 = calendar.getTime();
    assertTrue(DateUtils.sameDate(date1, date1, format));

    // 月份从0开始: 2017-05-20 15:50
    calendar.set(2017, 04, 20, 15, 50);
    Date date2 = calendar.getTime();
    assertFalse(DateUtils.sameDate(date1, date2, format));

    // 月份从0开始: 2017-04-20 18:50
    calendar.set(2017, 03, 20, 18, 50);
    date2 = calendar.getTime();
    assertFalse(DateUtils.sameDate(date1, date2, format));

    format = "yyyyMMdd";
    // 月份从0开始: 2017-04-20 18:50
    calendar.set(2017, 03, 20, 18, 50);
    date2 = calendar.getTime();
    assertTrue(DateUtils.sameDate(date1, date2, format));
}
项目:Udhari    文件:DatePickerFragment.java   
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    final Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);


    // Create a new instance of DatePickerDialog and return it
    DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
            (DatePickerDialog.OnDateSetListener) getActivity(), year, month, day);
    c.set(Calendar.HOUR_OF_DAY, 12);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    datePickerDialog.getDatePicker().setMinDate(c.getTimeInMillis());
    return datePickerDialog;
}
项目:openjdk-jdk10    文件:CalendarRegression.java   
/**
 * 4655637: Calendar.set() for DAY_OF_WEEK does not return the right value
 *
 * <p>Need to use SimpleDateFormat to test because a call to
 * get(int) changes internal states of a Calendar.
 */
public void Test4655637() {
    Locale locale = Locale.getDefault();
    if (!TestUtils.usesGregorianCalendar(locale)) {
        logln("Skipping this test because locale is " + locale);
        return;
    }

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date(1029814211523L));
    cal.set(YEAR, 2001);
    Date t = cal.getTime();
    cal.set(MONTH, JANUARY);
    t = cal.getTime();

    cal.set(DAY_OF_MONTH, 8);
    t = cal.getTime();

    cal.set(DAY_OF_WEEK, MONDAY);
    DateFormat df = new SimpleDateFormat("yyyy/MM/dd", Locale.US);
    String expected = "2001/01/08";
    String s = df.format(cal.getTime());
    if (!expected.equals(s)) {
        errln("expected: " + expected + ", got: " + s);
    }
}
项目:liveomvp    文件:DateUtil.java   
public static String getMonth(String date) {
    if (TextUtils.isEmpty(date)) {
        return "";
    }

    Calendar dateTime = Calendar.getInstance();

    try {
        dateTime.setTime(getDate(date));
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMM", Locale.getDefault());
        return simpleDateFormat.format(dateTime.getTime());

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return "";
}
项目:AndiCar    文件:Utils.java   
/**
 * Round Up (24:00) or Down (00:00) a datetime
 *
 * @param dateTimeInMillis the datetime in milliseconds
 * @param decodeType       type of decode. See StaticValues.dateDecodeType...
 */
//old name: decodeDateStr
@SuppressLint("WrongConstant")
@SuppressWarnings("SameParameterValue")
public static long roundDate(long dateTimeInMillis, String decodeType) {
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(dateTimeInMillis);
    if (decodeType.equals(ConstantValues.DATE_DECODE_TO_ZERO)) {
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
    }
    else if (decodeType.equals(ConstantValues.DATE_DECODE_TO_24)) {
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MILLISECOND, 999);
    }
    return cal.getTimeInMillis();
}
项目:alfresco-repository    文件:FreeMarkerModelLuceneFunctionTest.java   
/**
 * Test generation of lucene date ranges
 *
 */
public void testLuceneDateRangeFunction()
{
    GregorianCalendar cal = new GregorianCalendar();
    cal.set(Calendar.YEAR, 2001);
    cal.set(Calendar.MONTH, 1);
    cal.set(Calendar.DAY_OF_MONTH, 1);
    String isoStartDate = ISO8601DateFormat.format(cal.getTime());
    cal.add(Calendar.DAY_OF_MONTH, 1);
    String isoEndDate = ISO8601DateFormat.format(cal.getTime());
    String template = "${luceneDateRange(\""+isoStartDate+"\", \"P1D\")}";
    FreeMarkerWithLuceneExtensionsModelFactory mf = new FreeMarkerWithLuceneExtensionsModelFactory();
    mf.setServiceRegistry(serviceRegistry);
    String result = serviceRegistry.getTemplateService().processTemplateString("freemarker", template, mf.getModel());
    assertEquals(result, "["+isoStartDate+" TO "+isoEndDate+"]");
}
项目:jobManage    文件:UtilHelper.java   
public static Integer countDiffDay(String startDate, String endDate) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance(); 
    long fTime = 0;
    long oTime = 0;
      try {
    cal.setTime(sdf.parse(startDate));
       fTime = cal.getTimeInMillis();

       cal.setTime(sdf.parse(endDate));    
       oTime = cal.getTimeInMillis();  
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}    

      long between_days=(oTime-fTime)/(1000*3600*24); 
    return Integer.parseInt(String.valueOf(between_days));
  }
项目:minu-poska-android    文件:DateUtils.java   
/**
 * Determines whether or not a date has any time values.
 * 
 * @param date
 *            The date.
 * @return true iff the date is not null and any of the date's hour, minute,
 *         seconds or millisecond values are greater than zero.
 */
public static boolean hasTime(Date date) {
    if (date == null) {
        return false;
    }
    Calendar c = Calendar.getInstance();
    c.setTime(date);
    if (c.get(Calendar.HOUR_OF_DAY) > 0) {
        return true;
    }
    if (c.get(Calendar.MINUTE) > 0) {
        return true;
    }
    if (c.get(Calendar.SECOND) > 0) {
        return true;
    }
    if (c.get(Calendar.MILLISECOND) > 0) {
        return true;
    }
    return false;
}
项目:RLibrary    文件:TimeUtil.java   
public static String getBeijingNowTimeString(String format) {
    TimeZone timezone = TimeZone.getTimeZone("Asia/Shanghai");

    Date date = new Date(currentTimeMillis());
    SimpleDateFormat formatter = new SimpleDateFormat(format, Locale.getDefault());
    formatter.setTimeZone(timezone);

    GregorianCalendar gregorianCalendar = new GregorianCalendar();
    gregorianCalendar.setTimeZone(timezone);
    String prefix = gregorianCalendar.get(Calendar.AM_PM) == Calendar.AM ? "上午" : "下午";

    return prefix + formatter.format(date);
}
项目:ApplicationDetection    文件:AsyncTaskService.java   
/**
 * 检测主机cpu使用状态
 * @param res
 */
@Async
public void executeAsyncTaskFour(ManagerTomcatEntity res){
   try {

       SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
       HostCpuResultEntity cpuInfo = new HostCpuResultEntity();
       cpuInfo.setId(UUIDUtil.generate());
       cpuInfo.setTomcatId(res.getId());
       cpuInfo.setIp(res.getIp());
       Calendar cal = Calendar.getInstance(TimeZone.getDefault());
       cpuInfo.setTime(System.currentTimeMillis() / 1000 * 1000 + cal.getTimeZone().getRawOffset());
       cpuInfo.setTimeText(dateFormat.format(new Date()));
       String userName = res.getHostUser();
       String password = res.getHostPassword();
       String ip = res.getIp();
       String result = SSHUtil.getCpuInfo(userName, password, ip);
       if (result == null) {
           cpuInfo.setResult("ssh连接失败!");
       } else if ("错误:该主机下含有多个tomcat应用!".equals(result)) {
           cpuInfo.setResult("错误:该主机下含有多个tomcat应用!");
       } else {
           cpuInfo.setResult("200");
           cpuInfo.setCpuInfo(Double.parseDouble(result));
       }
       res.setHostCpuResultEntity(cpuInfo);
   }catch (Exception e){
       e.printStackTrace();
   }finally {
       res.setCpuStatus(true);
   }
}
项目:Spring-Security-Third-Edition    文件:EventsController.java   
/**
 * Populates the form for creating an event with valid information. Useful so that users do not have to think when
 * filling out the form for testing.
 *
 * @param createEventForm
 * @return
 */
@PostMapping(value = "/new", params = "auto")
public String createEventFormAutoPopulate(@ModelAttribute CreateEventForm createEventForm) {
    // provide default values to make user submission easier
    createEventForm.setSummary("A new event....");
    createEventForm.setDescription("This was autopopulated to save time creating a valid event.");
    createEventForm.setWhen(Calendar.getInstance());

    // make the attendee not the current user
    CalendarUser currentUser = userContext.getCurrentUser();
    int attendeeId = currentUser.getId() == 0 ? 1 : 0;
    CalendarUser attendee = calendarService.getUser(attendeeId);
    createEventForm.setAttendeeEmail(attendee.getEmail());

    return "events/create";
}
项目:GoupilBot    文件:DateTimeLib.java   
/**
 * Retourne un tableau d'entiers avec le jour, le mois, l'année, l'heure,
 * les minutes, les secondes et les milisecondes de la date spécifiée
 * en paramètre.
 *
 * @param date une date de type java.util.Date
 * @return un tableau[7] avec JJ, MM, AA, hh, mm, ss, ms
 */
public static int[] extractDateTimeInfo(Date date) {
  int[] info = new int[] {-1, -1, -1, -1, -1, -1, -1};
  if (date != null) {
    Calendar c = new GregorianCalendar();
    c.setTime(date);
    info[0] = c.get(Calendar.DAY_OF_MONTH);
    info[1] = c.get(Calendar.MONTH) + 1;
    info[2] = c.get(Calendar.YEAR);
    info[3] = c.get(Calendar.HOUR_OF_DAY);
    info[4] = c.get(Calendar.MINUTE);
    info[5] = c.get(Calendar.SECOND);
    info[6] = c.get(Calendar.MILLISECOND);
  }
  return info;
}
项目:Spring-Security-Third-Edition    文件:EventsController.java   
/**
 * Populates the form for creating an event with valid information. Useful so that users do not have to think when
 * filling out the form for testing.
 *
 * @param createEventForm
 * @return
 */
@PostMapping(value = "/new", params = "auto")
public String createEventFormAutoPopulate(@ModelAttribute CreateEventForm createEventForm) {
    // provide default values to make user submission easier
    createEventForm.setSummary("A new event....");
    createEventForm.setDescription("This was autopopulated to save time creating a valid event.");
    createEventForm.setWhen(Calendar.getInstance());

    // make the attendee not the current user
    CalendarUser currentUser = userContext.getCurrentUser();
    int attendeeId = currentUser.getId() == 0 ? 1 : 0;
    CalendarUser attendee = calendarService.getUser(attendeeId);
    createEventForm.setAttendeeEmail(attendee.getEmail());

    return "events/create";
}
项目:odoo-work    文件:TypeAdapters.java   
@Override
public void write(JsonWriter out, Calendar value) throws IOException {
  if (value == null) {
    out.nullValue();
    return;
  }
  out.beginObject();
  out.name(YEAR);
  out.value(value.get(Calendar.YEAR));
  out.name(MONTH);
  out.value(value.get(Calendar.MONTH));
  out.name(DAY_OF_MONTH);
  out.value(value.get(Calendar.DAY_OF_MONTH));
  out.name(HOUR_OF_DAY);
  out.value(value.get(Calendar.HOUR_OF_DAY));
  out.name(MINUTE);
  out.value(value.get(Calendar.MINUTE));
  out.name(SECOND);
  out.value(value.get(Calendar.SECOND));
  out.endObject();
}
项目:Swap    文件:DateUtil.java   
/**
 * 两个日期之间相差的月数
 * @param startDate
 * @param endDate
 * @return
 */
public int betweenDurations(String startDate, String endDate){

    int month = 0;
    int day = 0;

    SimpleDateFormat sdf = new SimpleDateFormat(DateFormat.YYYY_MM_DD.getValue());
    Calendar startCalendar = Calendar.getInstance();
    Calendar endCalendar = Calendar.getInstance();
    try {
        startCalendar.setTime(sdf.parse(startDate));
        endCalendar.setTime(sdf.parse(endDate));

        month = endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
        day = endCalendar.get(Calendar.DAY_OF_MONTH) - startCalendar.get(Calendar.DAY_OF_MONTH);
    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("date format exception, start date " + startDate + ", end date " + endDate);
    }

    if(day > 0){
        month = month + 1;
    }

    return month;
}
项目:cyberduck    文件:UnixFTPEntryParserTest.java   
@Test
public void testCurrentYear() {
    FTPFileEntryParser parser = new FTPParserSelector().getParser("UNIX");

    FTPFile parsed;

    parsed = parser.parseFTPEntry(
            "-rw-r--r--   1 20708    205             194 Oct 17 14:40 D3I0_805.fixlist");
    assertNotNull(parsed);
    assertTrue(parsed.isFile());
    assertNotNull(parsed.getTimestamp());
    assertEquals(Calendar.OCTOBER, parsed.getTimestamp().get(Calendar.MONTH));
    assertEquals(17, parsed.getTimestamp().get(Calendar.DAY_OF_MONTH));
    assertEquals(14, parsed.getTimestamp().get(Calendar.HOUR_OF_DAY));
    assertEquals(40, parsed.getTimestamp().get(Calendar.MINUTE));
}
项目:personium-core    文件:UpdateTest.java   
/**
 * Cell更新のリクエストボディに__metadataを指定した場合に400が返却されること.
 */
@SuppressWarnings("unchecked")
@Test
public final void Cell更新のリクエストボディに__metadataを指定した場合に400が返却されること() {

    // Cellを更新
    // リクエストヘッダをセット
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HttpHeaders.AUTHORIZATION, BEARER_MASTER_TOKEN);
    headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    headers.put(HttpHeaders.IF_MATCH, "*");

    // リクエストボディを生成
    JSONObject requestBody = new JSONObject();
    String updateCellName = "cellname" + Long.toString(Calendar.getInstance().getTimeInMillis());
    requestBody.put("Name", updateCellName);
    requestBody.put(METADATA, "test");

    res = updateCell(headers, requestBody);

    // Cell更新のレスポンスチェック
    assertEquals(HttpStatus.SC_BAD_REQUEST, res.getStatusCode());
    assertEquals(MediaType.APPLICATION_JSON, res.getResponseHeaders(HttpHeaders.CONTENT_TYPE)[0].getValue());
}
项目:OSchina_resources_android    文件:StringUtils.java   
/**
 * @param calendar {@link Calendar}
 * @return 今天, 昨天, 前天, n天前
 */
public static String formatSomeDay(Calendar calendar) {
    if (calendar == null) return "?天前";
    Calendar mCurrentDate = Calendar.getInstance();
    long crim = mCurrentDate.getTimeInMillis(); // current
    long trim = calendar.getTimeInMillis(); // target
    long diff = crim - trim;

    int year = mCurrentDate.get(Calendar.YEAR);
    int month = mCurrentDate.get(Calendar.MONTH);
    int day = mCurrentDate.get(Calendar.DATE);

    mCurrentDate.set(year, month, day, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
        return "今天";
    }
    mCurrentDate.set(year, month, day - 1, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
        return "昨天";
    }
    mCurrentDate.set(year, month, day - 2, 0, 0, 0);
    if (trim >= mCurrentDate.getTimeInMillis()) {
        return "前天";
    }
    return String.format("%s天前", diff / AlarmManager.INTERVAL_DAY);
}
项目:yaacc-code    文件:UpnpClient.java   
/**
 * Returns all player instances initialized with the given didl object
 *
 * @param items the items to be played
 * @return the player
 */
public List<Player> initializePlayers(List<Item> items) {
    LinkedList<PlayableItem> playableItems = new LinkedList<PlayableItem>();

    for (Item currentItem : items) {
        PlayableItem playableItem = new PlayableItem(currentItem, getDefaultDuration());
        playableItems.add(playableItem);
    }
    SynchronizationInfo synchronizationInfo = new SynchronizationInfo();
    synchronizationInfo.setOffset(getDeviceSyncOffset()); //device specific offset

    Calendar now = Calendar.getInstance(Locale.getDefault());
    now.add(Calendar.MILLISECOND, Integer.valueOf(preferences.getString(context.getString(R.string.settings_default_playback_delay_key), "0")));
    String referencedPresentationTime = new SyncOffset(true, now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND), now.get(Calendar.MILLISECOND), 0, 0).toString();
    Log.d(getClass().getName(), "CurrentTime: " + new Date().toString() + " representationTime: " + referencedPresentationTime);
    synchronizationInfo.setReferencedPresentationTime(referencedPresentationTime);

    return PlayerFactory.createPlayer(this, synchronizationInfo, playableItems);
}
项目:incubator-netbeans    文件:PacUtilsDateTimeTest.java   
/**
 * Test of isInWeekdayRange method, of class PacUtilsDateTime.
 */
@Test
public void testIsInWeekdayRange() throws Exception {
    System.out.println("isInWeekdayRange");
    Calendar cal = Calendar.getInstance();
    int weekdayNum = cal.get(Calendar.DAY_OF_WEEK);
    Date[] dates = new Date[7];
    dates[weekdayNum-1] = cal.getTime();
    for(int i=weekdayNum+1; i <= 7; i++) {
        cal.add(Calendar.DATE, 1);
        dates[i-1] = cal.getTime();
    }
    cal = Calendar.getInstance();
    for(int i=weekdayNum-1; i >=1; i--) {
        cal.add(Calendar.DATE, -1);
        dates[i-1] = cal.getTime();
    }

    Date nowSUN = dates[0];
    Date nowMON = dates[1];
    Date nowTUE = dates[2];
    Date nowWED = dates[3];
    Date nowTHU = dates[4];
    Date nowFRI = dates[5];
    Date nowSAT = dates[6];

    assertTrue(PacUtilsDateTime.isInWeekdayRange(nowMON, "MON"));
    assertFalse(PacUtilsDateTime.isInWeekdayRange(nowMON, "SUN"));
    assertTrue(PacUtilsDateTime.isInWeekdayRange(nowMON, "MON", "SUN"));
    assertTrue(PacUtilsDateTime.isInWeekdayRange(nowSAT, "FRI", "TUE"));
    assertTrue(PacUtilsDateTime.isInWeekdayRange(nowMON, "FRI", "TUE"));
    assertFalse(PacUtilsDateTime.isInWeekdayRange(nowTHU, "FRI", "TUE"));
    assertFalse(PacUtilsDateTime.isInWeekdayRange(nowTHU, "SAT", "MON"));
    assertTrue(PacUtilsDateTime.isInWeekdayRange(nowSUN, "SAT", "MON", "GMT"));
    assertFalse(PacUtilsDateTime.isInWeekdayRange(nowSUN, "MON", "TUE", "GMT"));

}
项目:Spring-Security-Third-Edition    文件:JpaEventDao.java   
@Override
public int createEvent(final Event event) {
    if (event == null) {
        throw new IllegalArgumentException("event cannot be null");
    }
    if (event.getId() != null) {
        throw new IllegalArgumentException("event.getId() must be null when creating a new Message");
    }
    final CalendarUser owner = event.getOwner();
    if (owner == null) {
        throw new IllegalArgumentException("event.getOwner() cannot be null");
    }
    final CalendarUser attendee = event.getAttendee();
    if (attendee == null) {
        throw new IllegalArgumentException("attendee.getOwner() cannot be null");
    }
    final Calendar when = event.getWhen();
    if(when == null) {
        throw new IllegalArgumentException("event.getWhen() cannot be null");
    }
    Event newEvent = repository.save(event);
    return newEvent.getId();
}
项目:GitHub    文件:DiskCache.java   
public void put(String key, String value, long expireMills) {
    if (TextUtils.isEmpty(key) || TextUtils.isEmpty(value)) return;

    String name = getMd5Key(key);
    try {
        if (!TextUtils.isEmpty(get(name))) {     //如果存在,先删除
            cache.remove(name);
        }

        DiskLruCache.Editor editor = cache.edit(name);
        StringBuilder content = new StringBuilder(value);
        content.append(TAG_CACHE.replace("createTime_v", "" + Calendar.getInstance().getTimeInMillis()).replace("expireMills_v", "" + expireMills));
        editor.set(0, content.toString());
        editor.commit();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
项目:the-vigilantes    文件:ResultSetRow.java   
/**
 * @param columnIndex
 * @param bits
 * @param offset
 * @param length
 * @param targetCalendar
 * @param tz
 * @param rollForward
 * @param conn
 * @param rs
 * @throws SQLException
 */
protected Time getNativeTime(int columnIndex, byte[] bits, int offset, int length, Calendar targetCalendar, TimeZone tz, boolean rollForward,
        MySQLConnection conn, ResultSetImpl rs) throws SQLException {

    int hour = 0;
    int minute = 0;
    int seconds = 0;

    if (length != 0) {
        // bits[0] // skip tm->neg
        // binaryData.readLong(); // skip daysPart
        hour = bits[offset + 5];
        minute = bits[offset + 6];
        seconds = bits[offset + 7];
    }

    if (!rs.useLegacyDatetimeCode) {
        return TimeUtil.fastTimeCreate(hour, minute, seconds, targetCalendar, this.exceptionInterceptor);
    }

    Calendar sessionCalendar = rs.getCalendarInstanceForSessionOrNew();

    Time time = TimeUtil.fastTimeCreate(sessionCalendar, hour, minute, seconds, this.exceptionInterceptor);

    Time adjustedTime = TimeUtil.changeTimezone(conn, sessionCalendar, targetCalendar, time, conn.getServerTimezoneTZ(), tz, rollForward);

    return adjustedTime;
}
项目:xlight_android_native    文件:DateUtil.java   
private static int getYearPlus() {
    Calendar cd = Calendar.getInstance();
    int yearOfNumber = cd.get(Calendar.DAY_OF_YEAR);// 获得当天是一年中的第几天
    cd.set(Calendar.DAY_OF_YEAR, 1);// 把日期设为当年第一天
    cd.roll(Calendar.DAY_OF_YEAR, -1);// 把日期回滚一天。
    int MaxYear = cd.get(Calendar.DAY_OF_YEAR);
    if (yearOfNumber == 1) {
        return -MaxYear;
    } else {
        return 1 - yearOfNumber;
    }
}
项目:GitHub    文件:DatePickerDialog.java   
public void onDayOfMonthSelected(int year, int month, int day) {
    mCalendar.set(Calendar.YEAR, year);
    mCalendar.set(Calendar.MONTH, month);
    mCalendar.set(Calendar.DAY_OF_MONTH, day);
    updatePickers();
    updateDisplay(true);

       if(mCloseOnSingleTapDay) {
           onDoneButtonClick();
       }
}
项目:stynico    文件:DateHelper.java   
/**
    * 得到这个月有多少天
    * 
    * @param year
    * @param month
    * @return
    */
   public int getMonthLastDay(int year, int month)
{
       if (month == 0)
    {
           return 0;
       }
       Calendar a = Calendar.getInstance();
       a.set(Calendar.YEAR, year);
       a.set(Calendar.MONTH, month - 1);
       a.set(Calendar.DATE, 1);// 把日期设置为当月第一天
       a.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天
       int maxDate = a.get(Calendar.DATE);
       return maxDate;
   }
项目:CalendarCheck    文件:SimpleMonthView.java   
private void drawMonthDayLabels(Canvas canvas) {
    //int y = MONTH_HEADER_HEIGHT - (WEEK_NAME_BAR_SIZE / 2);
    int y = MONTH_HEADER_HEIGHT + (WEEK_NAME_BAR_SIZE / 2);
    int dayWidthHalf = (mWidth - mPadding * 2) / (mNumDays * 2);
    String[] shortWeekdays = mDateFormatSymbols.getShortWeekdays();
    for (int i = 0; i < mNumDays; i++) {
        int calendarDay = (i + mWeekStart) % mNumDays;
        int x = (2 * i + 1) * dayWidthHalf + mPadding;
        mDayLabelCalendar.set(Calendar.DAY_OF_WEEK, calendarDay);
        //Log.d("sie", "星期的文字 -- " + shortWeekdays[mDayLabelCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()));
        canvas.drawText(shortWeekdays[mDayLabelCalendar.get(Calendar.DAY_OF_WEEK)].toUpperCase(Locale.getDefault()), x, y, mWeekPaint);
    }
}
项目:leoapp-sources    文件:SQLiteConnectorKlausurplan.java   
private String getDate() {
    Calendar calendar = new GregorianCalendar();
    if (calendar.get(Calendar.HOUR_OF_DAY) >= 15) {
        calendar.add(Calendar.DAY_OF_MONTH, 1);
    }
    return dateFormat.format(calendar.getTime());
}
项目:unitimes    文件:ExamPeriod.java   
public static Date[] getBounds(Long sessionId, Date examBeginDate, Long examTypeId) {
    Object[] bounds = (Object[])new ExamPeriodDAO().getQuery("select min(ep.dateOffset), min(ep.startSlot - ep.eventStartOffset), max(ep.dateOffset), max(ep.startSlot+ep.length+ep.eventStopOffset) " +
            "from ExamPeriod ep where ep.session.uniqueId = :sessionId and ep.examType.uniqueId = :examTypeId")
            .setLong("sessionId", sessionId)
            .setLong("examTypeId", examTypeId)
            .setCacheable(true).uniqueResult();
    if (bounds == null || bounds[0] == null) return null;
    int minDateOffset = ((Number)bounds[0]).intValue();
    int minSlot = ((Number)bounds[1]).intValue();
    int minHour = (Constants.SLOT_LENGTH_MIN*minSlot+Constants.FIRST_SLOT_TIME_MIN) / 60;
    int minMin = (Constants.SLOT_LENGTH_MIN*minSlot+Constants.FIRST_SLOT_TIME_MIN) % 60;
    int maxDateOffset = ((Number)bounds[2]).intValue();
    int maxSlot = ((Number)bounds[3]).intValue();
    int maxHour = (Constants.SLOT_LENGTH_MIN*maxSlot+Constants.FIRST_SLOT_TIME_MIN) / 60;
    int maxMin = (Constants.SLOT_LENGTH_MIN*maxSlot+Constants.FIRST_SLOT_TIME_MIN) % 60;
    Calendar c = Calendar.getInstance(Locale.US);
    c.setTime(examBeginDate);
    c.add(Calendar.DAY_OF_YEAR, minDateOffset);
    c.set(Calendar.HOUR, minHour);
    c.set(Calendar.MINUTE, minMin);
    Date min = c.getTime();
    c.setTime(examBeginDate);
    c.add(Calendar.DAY_OF_YEAR, maxDateOffset);
    c.set(Calendar.HOUR, maxHour);
    c.set(Calendar.MINUTE, maxMin);
    Date max = c.getTime();
    return new Date[] {min, max};
}
项目:Chore-Manager-App    文件:SpecificChoreActivity.java   
public void onClickCompleteChore(View view){

        Intent i = getIntent();
        Chore chore = (Chore) i.getSerializableExtra("ChoreInfo"); //Serilizable Chore
        User currentUser = MenuActivity.getManager().getCurrentUser(); //Getting Current User
        chore = currentUser.getChoreFromId(chore.getChoreId()); //Actual Chore

        if(chore != null){
            if(chore.getStatusString().equals("Complete")){ //IF already done
                Snackbar.make(view, "Already Completed", Snackbar.LENGTH_LONG).setAction("Action",null).show();
            }
            else{
                if(Calendar.getInstance().getTime().compareTo(chore.getDeadline()) <= 0){
                    Snackbar.make(view, "You have received "+ currentUser.completeChore(chore) +" points!", Snackbar.LENGTH_LONG)
                            .setAction("Action",null).show();
                    setStatusText(chore.getStatusString());
                }
                else{
                    Snackbar.make(view, "You completed it late, you get half points: "+ currentUser.completeChoreLate(chore), Snackbar.LENGTH_LONG)
                            .setAction("Action",null).show();
                    setStatusText(chore.getStatusString());
                }
                MenuActivity.getManager().addFinishedChores(chore);

            }

        }
        else{
            Snackbar.make(view, "NOT ASSIGNED TO YOU!", Snackbar.LENGTH_LONG).setAction("Action",null).show();
        }

        MenuActivity.getFbRef().child(MenuActivity.getEmail()).child("ChoreManager").setValue(MenuActivity.getManager());
    }
项目:lams    文件:PreparedStatementWrapper.java   
public void setDate(int parameterIndex, Date x, Calendar cal) throws SQLException {
    try {
        if (this.wrappedStmt != null) {
            ((PreparedStatement) this.wrappedStmt).setDate(parameterIndex, x, cal);
        } else {
            throw SQLError.createSQLException("No operations allowed after statement closed", SQLError.SQL_STATE_GENERAL_ERROR, this.exceptionInterceptor);
        }
    } catch (SQLException sqlEx) {
        checkAndFireConnectionError(sqlEx);
    }
}
项目:MyFire    文件:TimeUtil.java   
public static String getCurrentDay2() {
    String curDateTime = null;
    try {
        SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat(dateFormatYMDHMS);
        Calendar c = new GregorianCalendar();
        c.add(Calendar.DAY_OF_MONTH, 0);
        curDateTime = mSimpleDateFormat.format(c.getTime());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return curDateTime;
}
项目:belling-spring-rabbitmq    文件:TimeUtils.java   
private static int getSundayAdd() {

        Calendar cal = Calendar.getInstance();
        int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);

        if (dayOfWeek == 1) {
            return 7;
        } else {
            return 7 - dayOfWeek + 1;
        }
    }
项目:OAuth-2.0-Cookbook    文件:OAuth2ClientTokenSevices.java   
@Override
public void saveAccessToken(OAuth2ProtectedResourceDetails resource,
        Authentication authentication, OAuth2AccessToken accessToken) {
    Calendar expirationDate = Calendar.getInstance();
    expirationDate.setTime(accessToken.getExpiration());

    settings.setAccessToken(accessToken.getValue());
    settings.setExpiresIn(expirationDate);
}
项目:DateRangePickerLibrary    文件:MonthView.java   
public static MonthView create(ViewGroup parent, LayoutInflater inflater,
                               DateFormat weekdayNameFormat, Listener listener, Calendar today, int dividerColor,
                               int dayBackgroundResId, int dayTextColorResId, int titleTextColor, boolean displayHeader,
                               int headerTextColor, List<CalendarCellDecorator> decorators, Locale locale,
                               DayViewAdapter adapter) {
  final MonthView view = (MonthView) inflater.inflate(R.layout.month, parent, false);
  view.setDayViewAdapter(adapter);
  view.setDividerColor(dividerColor);
  view.setDayTextColor(dayTextColorResId);
  view.setTitleTextColor(titleTextColor);
  view.setDisplayHeader(displayHeader);
  view.setHeaderTextColor(headerTextColor);

  if (dayBackgroundResId != 0) {
    view.setDayBackground(dayBackgroundResId);
  }

  final int originalDayOfWeek = today.get(Calendar.DAY_OF_WEEK);

  view.isRtl = isRtl(locale);
  view.locale = locale;
  int firstDayOfWeek = today.getFirstDayOfWeek();
  final CalendarRowView headerRow = (CalendarRowView) view.grid.getChildAt(0);
  for (int offset = 0; offset < 7; offset++) {
    today.set(Calendar.DAY_OF_WEEK, getDayOfWeek(firstDayOfWeek, offset, view.isRtl));
    final TextView textView = (TextView) headerRow.getChildAt(offset);
    textView.setText(weekdayNameFormat.format(today.getTime()));
  }
  today.set(Calendar.DAY_OF_WEEK, originalDayOfWeek);
  view.listener = listener;
  view.decorators = decorators;
  return view;
}
项目:Pluto-Android    文件:DateUtil.java   
/**
 * 日期间隔计算
 * 计算公式(示例):
 * 20121201- 20121212
 * 取出20121201这一年过了多少天 d1 = 天数  取出20121212这一年过了多少天 d2 = 天数
 * 如果2012年这一年有366天就要让间隔的天数+1,因为2月份有29日。
 *
 * @param maxDays  用于记录一年中有365天还是366天
 * @param d1       表示在这年中过了多少天
 * @param d2       表示在这年中过了多少天
 * @param y1       当前为2012年
 * @param y2       当前为2012年
 * @param calendar 根据日历对象来获取一年中有多少天
 * @return 计算后日期间隔的天数
 */
public static int numerical(int maxDays, int d1, int d2, int y1, int y2, Calendar calendar) {
    int day = d1 - d2;
    int betweenYears = y1 - y2;
    List<Integer> d366 = new ArrayList<>();

    if (calendar.getActualMaximum(Calendar.DAY_OF_YEAR) == 366) {
        System.out.println(calendar.getActualMaximum(Calendar.DAY_OF_YEAR));
        day += 1;
    }

    for (int i = 0; i < betweenYears; i++) {
        // 当年 + 1 设置下一年中有多少天
        calendar.set(Calendar.YEAR, (calendar.get(Calendar.YEAR)) + 1);
        maxDays = calendar.getActualMaximum(Calendar.DAY_OF_YEAR);
        // 第一个 366 天不用 + 1 将所有366记录,先不进行加入然后再少加一个
        if (maxDays != 366) {
            day += maxDays;
        } else {
            d366.add(maxDays);
        }
        // 如果最后一个 maxDays 等于366 day - 1
        if (i == betweenYears - 1 && betweenYears > 1 && maxDays == 366) {
            day -= 1;
        }
    }

    for (int i = 0; i < d366.size(); i++) {
        // 一个或一个以上的366天
        if (d366.size() >= 1) {
            day += d366.get(i);
        }
    }
    return day;
}
项目:BibliotecaPS    文件:ResultSetRow.java   
/**
 * @param columnIndex
 * @param bits
 * @param offset
 * @param length
 * @param conn
 * @param rs
 * @param cal
 * @throws SQLException
 */
protected java.sql.Date getNativeDate(int columnIndex, byte[] bits, int offset, int length, MySQLConnection conn, ResultSetImpl rs, Calendar cal)
        throws SQLException {

    int year = 0;
    int month = 0;
    int day = 0;

    if (length != 0) {
        year = (bits[offset + 0] & 0xff) | ((bits[offset + 1] & 0xff) << 8);

        month = bits[offset + 2];
        day = bits[offset + 3];
    }

    if (length == 0 || ((year == 0) && (month == 0) && (day == 0))) {
        if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_CONVERT_TO_NULL.equals(conn.getZeroDateTimeBehavior())) {
            return null;
        } else if (ConnectionPropertiesImpl.ZERO_DATETIME_BEHAVIOR_EXCEPTION.equals(conn.getZeroDateTimeBehavior())) {
            throw SQLError.createSQLException("Value '0000-00-00' can not be represented as java.sql.Date", SQLError.SQL_STATE_ILLEGAL_ARGUMENT,
                    this.exceptionInterceptor);
        }

        year = 1;
        month = 1;
        day = 1;
    }

    if (!rs.useLegacyDatetimeCode) {
        return TimeUtil.fastDateCreate(year, month, day, cal);
    }

    return rs.fastDateCreate(cal == null ? rs.getCalendarInstanceForSessionOrNew() : cal, year, month, day);
}
项目:parabuild-ci    文件:WeekTests.java   
/**
 * Some checks for the getStart() method.
 */
public void testGetStart() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.ITALY);
    Calendar cal = Calendar.getInstance(Locale.ITALY);
    cal.set(2006, Calendar.JANUARY, 16, 0, 0, 0);
    cal.set(Calendar.MILLISECOND, 0);
    Week w = new Week(3, 2006);
    assertEquals(cal.getTime(), w.getStart());
    Locale.setDefault(saved);        
}
项目:Spring-Security-Third-Edition    文件:JdbcEventDao.java   
@Override
public int createEvent(final Event event) {
    if (event == null) {
        throw new IllegalArgumentException("event cannot be null");
    }
    if (event.getId() != null) {
        throw new IllegalArgumentException("event.getId() must be null when creating a new Message");
    }
    final CalendarUser owner = event.getOwner();
    if (owner == null) {
        throw new IllegalArgumentException("event.getOwner() cannot be null");
    }
    final CalendarUser attendee = event.getAttendee();
    if (attendee == null) {
        throw new IllegalArgumentException("attendee.getOwner() cannot be null");
    }
    final Calendar when = event.getWhen();
    if(when == null) {
        throw new IllegalArgumentException("event.getWhen() cannot be null");
    }
    KeyHolder keyHolder = new GeneratedKeyHolder();
    this.jdbcOperations.update(new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
            PreparedStatement ps = connection.prepareStatement(
                    "insert into events (when,summary,description,owner,attendee) values (?, ?, ?, ?, ?)",
                    new String[] { "id" });
            ps.setDate(1, new java.sql.Date(when.getTimeInMillis()));
            ps.setString(2, event.getSummary());
            ps.setString(3, event.getDescription());
            ps.setInt(4, owner.getId());
            ps.setObject(5, attendee == null ? null : attendee.getId());
            return ps;
        }
    }, keyHolder);
    return keyHolder.getKey().intValue();
}
项目:xlight_android_native    文件:DateUtil.java   
private int getMonthPlus() {
    Calendar cd = Calendar.getInstance();
    int monthOfNumber = cd.get(Calendar.DAY_OF_MONTH);
    cd.set(Calendar.DATE, 1);// 把日期设置为当月第一天
    cd.roll(Calendar.DATE, -1);// 日期回滚一天,也就是最后一天
    MaxDate = cd.get(Calendar.DATE);
    if (monthOfNumber == 1) {
        return -MaxDate;
    } else {
        return 1 - monthOfNumber;
    }
}