Java Code Examples for java.util.Calendar

The following are top voted examples for showing how to use java.util.Calendar. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: CommonFramework   File: DateUtilsTest.java   View source code 7 votes vote down vote up
@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));
}
 
Example 2
Project: Udhari   File: DatePickerFragment.java   View source code 7 votes vote down vote up
@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;
}
 
Example 3
Project: openjdk-jdk10   File: CalendarRegression.java   View source code 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 4
Project: liveomvp   File: DateUtil.java   View source code 6 votes vote down vote up
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 "";
}
 
Example 5
Project: AndiCar   File: Utils.java   View source code 6 votes vote down vote up
/**
 * 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();
}
 
Example 6
Project: alfresco-repository   File: FreeMarkerModelLuceneFunctionTest.java   View source code 6 votes vote down vote up
/**
 * 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+"]");
}
 
Example 7
Project: jobManage   File: UtilHelper.java   View source code 6 votes vote down vote up
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));
  }
 
Example 8
Project: minu-poska-android   File: DateUtils.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 9
Project: RLibrary   File: TimeUtil.java   View source code 6 votes vote down vote up
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);
}
 
Example 10
Project: ApplicationDetection   File: AsyncTaskService.java   View source code 6 votes vote down vote up
/**
 * 检测主机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);
   }
}
 
Example 11
Project: Spring-Security-Third-Edition   File: EventsController.java   View source code 6 votes vote down vote up
/**
 * 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";
}
 
Example 12
Project: GoupilBot   File: DateTimeLib.java   View source code 6 votes vote down vote up
/**
 * 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;
}
 
Example 13
Project: Spring-Security-Third-Edition   File: EventsController.java   View source code 6 votes vote down vote up
/**
 * 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";
}
 
Example 14
Project: odoo-work   File: TypeAdapters.java   View source code 6 votes vote down vote up
@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();
}
 
Example 15
Project: Swap   File: DateUtil.java   View source code 6 votes vote down vote up
/**
 * 两个日期之间相差的月数
 * @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;
}
 
Example 16
Project: cyberduck   File: UnixFTPEntryParserTest.java   View source code 6 votes vote down vote up
@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));
}
 
Example 17
Project: personium-core   File: UpdateTest.java   View source code 6 votes vote down vote up
/**
 * 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());
}
 
Example 18
Project: OSchina_resources_android   File: StringUtils.java   View source code 6 votes vote down vote up
/**
 * @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);
}
 
Example 19
Project: yaacc-code   File: UpnpClient.java   View source code 6 votes vote down vote up
/**
 * 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);
}
 
Example 20
Project: incubator-netbeans   File: PacUtilsDateTimeTest.java   View source code 5 votes vote down vote up
/**
 * 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"));
    
}
 
Example 21
Project: Spring-Security-Third-Edition   File: JpaEventDao.java   View source code 5 votes vote down vote up
@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();
}
 
Example 22
Project: GitHub   File: DiskCache.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 23
Project: the-vigilantes   File: ResultSetRow.java   View source code 5 votes vote down vote up
/**
 * @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;
}
 
Example 24
Project: xlight_android_native   File: DateUtil.java   View source code 5 votes vote down vote up
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;
    }
}
 
Example 25
Project: GitHub   File: DatePickerDialog.java   View source code 5 votes vote down vote up
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();
       }
}
 
Example 26
Project: stynico   File: DateHelper.java   View source code 5 votes vote down vote up
/**
    * 得到这个月有多少天
    * 
    * @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;
   }
 
Example 27
Project: CalendarCheck   File: SimpleMonthView.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 28
Project: leoapp-sources   File: SQLiteConnectorKlausurplan.java   View source code 5 votes vote down vote up
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());
}
 
Example 29
Project: unitimes   File: ExamPeriod.java   View source code 5 votes vote down vote up
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};
}
 
Example 30
Project: Chore-Manager-App   File: SpecificChoreActivity.java   View source code 5 votes vote down vote up
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());
    }
 
Example 31
Project: lams   File: PreparedStatementWrapper.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 32
Project: MyFire   File: TimeUtil.java   View source code 5 votes vote down vote up
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;
}
 
Example 33
Project: belling-spring-rabbitmq   File: TimeUtils.java   View source code 5 votes vote down vote up
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;
		}
	}
 
Example 34
Project: OAuth-2.0-Cookbook   File: OAuth2ClientTokenSevices.java   View source code 5 votes vote down vote up
@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);
}
 
Example 35
Project: DateRangePickerLibrary   File: MonthView.java   View source code 5 votes vote down vote up
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;
}
 
Example 36
Project: Pluto-Android   File: DateUtil.java   View source code 5 votes vote down vote up
/**
 * 日期间隔计算
 * 计算公式(示例):
 * 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;
}
 
Example 37
Project: BibliotecaPS   File: ResultSetRow.java   View source code 5 votes vote down vote up
/**
 * @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);
}
 
Example 38
Project: parabuild-ci   File: WeekTests.java   View source code 5 votes vote down vote up
/**
 * 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);        
}
 
Example 39
Project: Spring-Security-Third-Edition   File: JdbcEventDao.java   View source code 5 votes vote down vote up
@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();
}
 
Example 40
Project: xlight_android_native   File: DateUtil.java   View source code 5 votes vote down vote up
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;
    }
}