Java Code Examples for java.util.Calendar.get()

The following are Jave code examples for showing how to use get() of the java.util.Calendar class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: mycat-src-1.6.1-RELEASE   File: PartitionByMonth.java   View Source Code Vote up 7 votes
@Override
public Integer[] calculateRange(String beginValue, String endValue) {
	try {
		int startPartition, endPartition;
		Calendar partitionTime = Calendar.getInstance();
		SimpleDateFormat format = new SimpleDateFormat(dateFormat);
		partitionTime.setTime(format.parse(beginValue));
		startPartition = ((partitionTime.get(Calendar.YEAR) - beginDate.get(Calendar.YEAR))
				* 12 + partitionTime.get(Calendar.MONTH)
				- beginDate.get(Calendar.MONTH));
		partitionTime.setTime(format.parse(endValue));
		endPartition = ((partitionTime.get(Calendar.YEAR) - beginDate.get(Calendar.YEAR))
				* 12 + partitionTime.get(Calendar.MONTH)
				- beginDate.get(Calendar.MONTH));

		List<Integer> list = new ArrayList<>();

		while (startPartition <= endPartition) {
			Integer nodeValue = reCalculatePartition(startPartition);
			if (Collections.frequency(list, nodeValue) < 1)
				list.add(nodeValue);
			startPartition++;
		}
		int size = list.size();
		return (list.toArray(new Integer[size]));
	} catch (ParseException e) {
		LOGGER.error(e);
		return new Integer[0];
	}
}
 
Example 2
Project: amap   File: MIP_TimeUtils.java   View Source Code Vote up 7 votes
/**
 * 获得指定日期的后一天
 * 
 * @param specifiedDay yyyy-mm-dd
 * @return
 */
public static String getSpecifiedDayAfter(String specifiedDay, SimpleDateFormat format)
{
    Calendar c = Calendar.getInstance();
    Date date = null;
    try
    {
        date = format.parse(specifiedDay);
    }
    catch (ParseException e)
    {
        e.printStackTrace();
    }
    c.setTime(date);
    int day = c.get(Calendar.DATE);
    c.set(Calendar.DATE, day + 1);
    
    String dayAfter = format.format(c.getTime());
    return dayAfter;
}
 
Example 3
Project: lams   File: JdbcDateTypeDescriptor.java   View Source Code Vote up 7 votes
@Override
public boolean areEqual(Date one, Date another) {
	if ( one == another ) {
		return true;
	}
	if ( one == null || another == null ) {
		return false;
	}

	if ( one.getTime() == another.getTime() ) {
		return true;
	}

	Calendar calendar1 = Calendar.getInstance();
	Calendar calendar2 = Calendar.getInstance();
	calendar1.setTime( one );
	calendar2.setTime( another );

	return calendar1.get( Calendar.MONTH ) == calendar2.get( Calendar.MONTH )
			&& calendar1.get( Calendar.DAY_OF_MONTH ) == calendar2.get( Calendar.DAY_OF_MONTH )
			&& calendar1.get( Calendar.YEAR ) == calendar2.get( Calendar.YEAR );
}
 
Example 4
Project: CIA   File: Profile.java   View Source Code Vote up 6 votes
/**
 * @param date is the day that habits need to be done on
 * @return a list of habits that need to be done on the specified day
 */
public List<Habit> getTodaysHabits(Date date){
    List<Habit> list = new ArrayList<>();
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    int today = calendar.get(Calendar.DAY_OF_WEEK);

    for (Habit habit : habits){
        // don't include habits that haven't begun yet
        if (habit.occursOn(today) && !date.before(habit.getStartDate()))
            list.add(habit);
    }

    return list;
}
 
Example 5
Project: SimpleERP   File: Chooser.java   View Source Code Vote up 6 votes
public DayLabel(Calendar cal){
    super(""+cal.get(Calendar.DAY_OF_MONTH), JLabel.CENTER);
    this.year = cal.get(Calendar.YEAR);
    this.month = cal.get(Calendar.MONTH);
    this.day = cal.get(Calendar.DAY_OF_MONTH);
    
    this.setFont(font);
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
    if(month == calendar.get(Calendar.MONTH)) this.setForeground(java.awt.Color.BLACK);
    else this.setForeground(java.awt.Color.LIGHT_GRAY);
    
}
 
Example 6
Project: openjdk-jdk10   File: ExsltDatetime.java   View Source Code Vote up 6 votes
/**
 * Parse the input string and return the corresponding calendar field
 * number.
 */
private static double getNumber(String in, String[] formats, int calField)
  throws ParseException
{
  Calendar cal = Calendar.getInstance();
  cal.setLenient(false);
  // Try the allowed formats, from longest to shortest.
  Date date = testFormats(in, formats);
  if (date == null) return Double.NaN;
  cal.setTime(date);
  return cal.get(calField);
}
 
Example 7
Project: kettle_support_kettle8.0   File: DateUtils.java   View Source Code Vote up 6 votes
/**
 * (季度)获取季度份时间段内的所有季度
 * 
 * @param StartDate
 * @param endDate
 * @return
 */
public static List<String> getQuarterBy(String StartDate, String beginQ,
		String endDate, String endQ) {
	DateFormat sdf = new SimpleDateFormat("yyyy-MM");
	Date date1 = null; // 开始日期
	Date dEnd = null; // 结束日期

	try {
		date1 = sdf.parse(StartDate);
		dEnd = sdf.parse(endDate);
	} catch (ParseException e) {
		e.printStackTrace();
	}

	Calendar calBegin = Calendar.getInstance();
	// 使用给定的 Date 设置此 Calendar 的时间
	calBegin.setTime(date1);
	Calendar calEnd = Calendar.getInstance();
	// 使用给定的 Date 设置此 Calendar 的时间
	calEnd.setTime(dEnd);
	List<String> list = new ArrayList<String>();
	int beginY = calBegin.get(Calendar.YEAR);
	int beginYQ = Integer.parseInt(beginQ);
	int endY = calEnd.get(Calendar.YEAR);
	int endYQ = Integer.parseInt(endQ);
	do {
		list.add(beginY + "年第" + beginYQ + "季度");
		if (beginY == endY && beginYQ == endYQ) {
			return list;
		}
		beginYQ++;
		if (beginYQ > 4) {
			beginYQ = 1;
			beginY++;
		}
	} while (true);
}
 
Example 8
Project: RunHDU   File: Utility.java   View Source Code Vote up 6 votes
/**
 * 获取特定类型的时间的字符串表示
 *
 * @param type 获取的时间类型,
 *             Types.TYPE_AM_PM:返回上午/下午/晚上
 *             Types.TYPE_MONTH_DATE:返回日期,例如2月15日
 *             Types.TYPE_CURRENT_TIME:返回时间,例如18:23
 *             其他类型:Calendar.TYPE
 * @return 类型字符串
 */
@SuppressLint("WrongConstant")
public static String getTime(int type) {
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());

    switch (type) {
        case Types.TYPE_AM_PM:
            int hour = calendar.get(Calendar.HOUR_OF_DAY);
            if (hour >= 6 && hour < 9) {
                return "早上";
            } else if (hour >= 9 && hour < 12) {
                return "上午";
            } else if (hour >= 12 && hour < 13) {
                return "中午";
            } else if (hour >= 13 && hour < 19) {
                return "下午";
            } else {
                return "晚上";
            }
        case Types.TYPE_MONTH_DATE:
            return new SimpleDateFormat("M月d日", Locale.getDefault()).format(new Date());
        case Types.TYPE_CURRENT_TIME:
            return new SimpleDateFormat("HH:mm", Locale.getDefault()).format(new Date());
        case Types.TYPE_MONTH:
            return String.valueOf(calendar.get(Calendar.MONTH) + 1);
        case Types.TYPE_STRING_FORM:
            return new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault()).format(new Date());
        default:
            return String.valueOf(calendar.get(type));
    }
}
 
Example 9
Project: logistimo-web-service   File: EventHandler.java   View Source Code Vote up 6 votes
public static Map<Integer, Duration> getDurations(CustomDuration customDuration, Long domainId) {
  // Get the durations
  Map<Integer, Duration> durations = new HashMap<Integer, Duration>();
  if (customDuration != null) {
    if (customDuration.duration != null) {
      durations.put(new Integer(customDuration.frequency), customDuration.duration);
    }
    return durations;
  }
  String timezone = DomainConfig.getInstance(domainId).getTimezone();
  // Get a day's time range (12am to 12am)
  Calendar cal = LocalDateUtil.getZeroTime(timezone);
  Duration daily = new Duration();
  cal.add(Calendar.DATE, -1);
  daily.start = cal.getTime();
  durations.put(new Integer(EventSpec.NotifyOptions.DAILY), daily); // add daily
  // Reset time to now
  cal = LocalDateUtil.getZeroTime(timezone);
  if (ConfigUtil.getBoolean("notifications.weekly", false)
      && cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY) {
    Duration weekly = new Duration();
    cal.add(Calendar.DATE, -7);
    weekly.start = cal.getTime();
    durations.put(new Integer(EventSpec.NotifyOptions.WEEKLY), weekly);
    // Reset time to now
    cal = LocalDateUtil.getZeroTime(timezone);
  }

  if (ConfigUtil.getBoolean("notifications.monthly", false)
      && cal.get(Calendar.DAY_OF_MONTH) == 1) {
    Duration monthly = new Duration();
    // Move calendar to last day of previous month
    cal.add(Calendar.MONTH, -1);
    monthly.start = cal.getTime();
    durations.put(new Integer(EventSpec.NotifyOptions.MONTHLY), monthly);
  }
  return durations;
}
 
Example 10
Project: WeatherAlarmClock   File: EditAlarmActivity.java   View Source Code Vote up 6 votes
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    final Calendar c = Calendar.getInstance();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    return new TimePickerDialog(getActivity(), this, hour, minute, DateFormat.is24HourFormat(getActivity()));
}
 
Example 11
Project: wall.e   File: DateKit.java   View Source Code Vote up 6 votes
/**
 * 获取上个月的最后第一天(最后的时刻23:59:59)
 * @return
 */
public static Date getLastMonthLastDay(){
	Calendar calendar = Calendar.getInstance();  
	int month = calendar.get(Calendar.MONTH);
	calendar.set(Calendar.MONTH, month - 1);
	calendar.set(Calendar.DAY_OF_MONTH,calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
	calendar.set(Calendar.HOUR_OF_DAY,23);
	calendar.set(Calendar.SECOND,59);
	calendar.set(Calendar.MINUTE,59);
	calendar.set(Calendar.MILLISECOND,0);
	return calendar.getTime();  
}
 
Example 12
Project: GitHub   File: TimeUtil.java   View Source Code Vote up 6 votes
/**获取智能生日
 * @param birthday
 * @param needYear
 * @return
 */
public static String getSmartBirthday(long birthday, boolean needYear) {
	int[] birthdayDetails = getDateDetail(birthday);
	int[] nowDetails = getDateDetail(System.currentTimeMillis());

	Calendar birthdayCalendar = Calendar.getInstance();
	birthdayCalendar.set(birthdayDetails[0], birthdayDetails[1], birthdayDetails[2]);

	Calendar nowCalendar = Calendar.getInstance();
	nowCalendar.set(nowDetails[0], nowDetails[1], nowDetails[2]);

	int days = birthdayCalendar.get(Calendar.DAY_OF_YEAR) - nowCalendar.get(Calendar.DAY_OF_YEAR);
	if (days < 8) {
		if (days >= 3) {
			return days + "天后";
		}
		if (days >= 2) {
			return TimeUtil.Day.NAME_THE_DAY_AFTER_TOMORROW;
		}
		if (days >= 1) {
			return TimeUtil.Day.NAME_TOMORROW;
		}
		if (days >= 0) {
			return TimeUtil.Day.NAME_TODAY;
		}
	}

	if (needYear) {
		return birthdayDetails[0] + "年" + birthdayDetails[1] + "月" + birthdayDetails[2] + "日";
	} 
	return birthdayDetails[1] + "月" + birthdayDetails[2] + "日";
}
 
Example 13
Project: NeuTV   File: Video.java   View Source Code Vote up 6 votes
private String getWeek(String pTime) {
    String Week = "";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar c = Calendar.getInstance();
    try {
        c.setTime(format.parse(pTime));
    } catch (ParseException e) {
        return null;
    }
    switch (c.get(Calendar.DAY_OF_WEEK)){
        case Calendar.SUNDAY:
            Week = "周日";
            break;
        case Calendar.MONDAY:
            Week = "周一";
            break;
        case Calendar.TUESDAY:
            Week = "周二";
            break;
        case Calendar.WEDNESDAY:
            Week = "周三";
            break;
        case Calendar.THURSDAY:
            Week = "周四";
            break;
        case Calendar.FRIDAY:
            Week = "周五";
            break;
        case Calendar.SATURDAY:
            Week = "周六";
            break;
    }
    return Week;
}
 
Example 14
Project: Weather-Android   File: MainActivity.java   View Source Code Vote up 6 votes
public static String formatTimeWithDayIfNotToday(Context context, long timeInMillis) {
    Calendar now = Calendar.getInstance();
    Calendar lastCheckedCal = new GregorianCalendar();
    lastCheckedCal.setTimeInMillis(timeInMillis);
    Date lastCheckedDate = new Date(timeInMillis);
    String timeFormat = android.text.format.DateFormat.getTimeFormat(context).format(lastCheckedDate);
    if (now.get(Calendar.YEAR) == lastCheckedCal.get(Calendar.YEAR) &&
            now.get(Calendar.DAY_OF_YEAR) == lastCheckedCal.get(Calendar.DAY_OF_YEAR)) {
        // Same day, only show time
        return timeFormat;
    } else {
        return android.text.format.DateFormat.getDateFormat(context).format(lastCheckedDate) + " " + timeFormat;
    }
}
 
Example 15
Project: Protestr   File: TimeUtils.java   View Source Code Vote up 5 votes
public static int getMinuteFromMillis(long timeInMillis) {
    final Calendar auxCalendar = Calendar.getInstance();
    auxCalendar.setTimeInMillis(timeInMillis);
    return auxCalendar.get(Calendar.MINUTE);
}
 
Example 16
Project: SER316-Ingolstadt   File: EventsPanel.java   View Source Code Vote up 5 votes
void newEventB_actionPerformed(ActionEvent e, String tasktext, Date startDate, Date endDate) {
  	EventDialog dlg = new EventDialog(App.getFrame(), Local.getString("New event"));
  	Dimension frmSize = App.getFrame().getSize();
  	Point loc = App.getFrame().getLocation();
  	if (tasktext != null) {
  		dlg.textField.setText(tasktext);
  	}
dlg.startDate.getModel().setValue(startDate);
dlg.endDate.getModel().setValue(endDate);
dlg.timeSpin.getModel().setValue(startDate);

  	dlg.setLocation((frmSize.width - dlg.getSize().width) / 2 + loc.x, (frmSize.height - dlg.getSize().height) / 2 + loc.y);
  	dlg.setEventDate(startDate);
dlg.setVisible(true);
  	if (dlg.CANCELLED)
  		return;
  	Calendar calendar = new GregorianCalendar(Local.getCurrentLocale()); //Fix deprecated methods to get hours
  	//by (jcscoobyrs) 14-Nov-2003 at 10:24:38 AM
  	calendar.setTime(((Date)dlg.timeSpin.getModel().getValue()));//Fix deprecated methods to get hours
  	//by (jcscoobyrs) 14-Nov-2003 at 10:24:38 AM
  	//JOSH CHANGED THIS
  	int hh = 12 + calendar.get(Calendar.HOUR_OF_DAY);//Fix deprecated methods to get hours
  	//if (hh > 12) {
  	//	hh = hh - 12;
  	//}
  	//by (jcscoobyrs) 14-Nov-2003 at 10:24:38 AM
  	int mm = calendar.get(Calendar.MINUTE);//Fix deprecated methods to get hours
  	//by (jcscoobyrs) 14-Nov-2003 at 10:24:38 AM
  	
  	//int hh = ((Date) dlg.timeSpin.getModel().getValue()).getHours();
  	//int mm = ((Date) dlg.timeSpin.getModel().getValue()).getMinutes();
  	String text = dlg.textField.getText();

CalendarDate eventCalendarDate = new CalendarDate(dlg.getEventDate());

  	if (dlg.noRepeatRB.isSelected())
  		EventsManager.createEvent(eventCalendarDate, hh, mm, text);
  	else {
  		updateEvents(dlg,hh,mm,text);
  	}
  	saveEvents();
  }
 
Example 17
Project: alchem   File: ProfitLossController.java   View Source Code Vote up 5 votes
public void datePicked()
{
    String date=profitDatePicker.getValue().toString();
    profitParticularDayList=FXCollections.observableArrayList();
    float totalSale=0,totalPurchase=0,profit=0.0f;
    try
    {
        Connection dbConnection = JDBC.databaseConnect();
        Statement sqlStatement = dbConnection.createStatement();
        ResultSet totalSaleResultSet=sqlStatement.executeQuery("SELECT SUM(total_amount) from retailer_sale_bill where date='"+date+"' AND user_access_id='" + user_id + "'");
        while (totalSaleResultSet.next())
        {
            totalSale=totalSaleResultSet.getFloat("sum");
        }
        ResultSet totalPurchaseResultSet=sqlStatement.executeQuery("SELECT SUM(total_amount) from retailer_purchase_bill where date='"+date+"' AND user_access_id='" + user_id + "'");
        while (totalPurchaseResultSet.next())
        {
            totalPurchase=totalPurchaseResultSet.getFloat("sum");
        }
        profit=totalSale-totalPurchase;
        profitParticularDayList.add(new ProfitLoss(date,totalSale,totalPurchase,profit));
    }catch (Exception e){
        e.printStackTrace();
    }
    Calendar dateToday= Calendar.getInstance();
    int year,day,month;
    String dateChk,tense;
    year = dateToday.get(Calendar.YEAR);
    month= dateToday.get(Calendar.MONTH)+1;
    day= dateToday.get(Calendar.DAY_OF_MONTH);
    dateChk=year+"-"+month+"-"+day;
    if(dateChk.equals(date))
        tense="is";
    else
        tense="was";

    profitTableView.setItems(profitParticularDayList);
    if(profit<0) {
        dateSelectedLabel.setText("Total Loss on " + date + " " + tense + " Rs." + (profit*-1));
        dateSelectedLabel.setTextFill(Color.RED);
    }
    else if(profit==0)
    {
        dateSelectedLabel.setText("No Profit or Loss on " + date);
        dateSelectedLabel.setTextFill(Color.WHITE);
    }
    else
    {
        dateSelectedLabel.setText("Total Profit on " + date + " " + tense + " Rs." + profit);
        dateSelectedLabel.setTextFill(Color.LIGHTGREEN);
    }
    datePickedHBox.setVisible(true);

}
 
Example 18
Project: marathonv5   File: SalesSimulator.java   View Source Code Vote up 5 votes
/** 
 * Generate data for the time period between the two given dates
 * 
 * This generates a large amount of sales and in the interest of time should
 * only be used with something such as the InitialLoadEntityManagerProxy that
 * culls the data in an intelligent way
 * 
 * @param start The date to start generating from
 * @param end The date to stop generating
 */
public void run(Date start, Date end) {
    System.out.println("SalesSimulator:: generating sales from ["+DATE_FORMAT.format(start) +"] to ["+DATE_FORMAT.format(end)+"]");
    // generate a sale every 6 seconds in the time range
    Calendar cal = Calendar.getInstance();
    cal.setTime(start);
    System.out.println("        Generated data for the day: ["+DATE_FORMAT.format(cal.getTime())+"]");
    int day = cal.get(Calendar.DAY_OF_YEAR);
    int hour = cal.get(Calendar.HOUR_OF_DAY);
    int year = cal.get(Calendar.YEAR);
    
    EntityTransaction et = em.getTransaction();
    
    et.begin();
    double time = start.getTime();
    Double d = Double.valueOf(time);
    double dailySalesRate = (TIME_BETWEEN_SALES * (1+salesRateAdjustment(d.longValue(), thisRandom)));
    
    while(time <= end.getTime()) {
        time = time + dailySalesRate;
        
        d = Double.valueOf(time);
        cal.setTimeInMillis(d.longValue());
        final int currentDay = cal.get(Calendar.DAY_OF_YEAR);
        final int currentHour = cal.get(Calendar.HOUR_OF_DAY);
        final int currentYear = cal.get(Calendar.YEAR);
        
        if (currentHour != hour) {
            hour = currentHour;
   //         System.out.println("                hour: ["+currentHour+":00]");
        }
        if (currentDay != day) {
            day = currentDay;
            System.out.println("        Generated data for the day: ["+DATE_FORMAT.format(cal.getTime())+"]");
            
            
            dailySalesRate = (TIME_BETWEEN_SALES * (1+salesRateAdjustment(d.longValue(), thisRandom)));
            salesPctAdjustment();
            //this flush works specifically with the InitialLoadEntityManagerProxy to ensure
            // that the data is loaded into DailySales in the correct order.
            em.flush();
            et.commit();
            em.clear();
            et.begin();
        }
        if (currentYear != year){
            year = currentYear;
        }
        
        generate(new Date(d.longValue()));
        
        
    }
    em.flush();
    et.commit();
    
}
 
Example 19
Project: 3way_laboratorios   File: UtilData.java   View Source Code Vote up 4 votes
public int getDia(Date data) {

		final Calendar calendario = Calendar.getInstance();

		calendario.setTime(data);

		return calendario.get(Calendar.DAY_OF_MONTH);
	}
 
Example 20
Project: 3way_laboratorios   File: UtilData.java   View Source Code Vote up 4 votes
public int getAno(Date data) {

		final Calendar calendario = Calendar.getInstance();

		calendario.setTime(data);

		return calendario.get(Calendar.YEAR);
	}