List of usage examples for java.util GregorianCalendar set
public void set(int field, int value)
From source file:CalendarTest.java
public static void main(String[] args) { // construct d as current date GregorianCalendar d = new GregorianCalendar(); int today = d.get(Calendar.DAY_OF_MONTH); int month = d.get(Calendar.MONTH); // set d to start date of the month d.set(Calendar.DAY_OF_MONTH, 1); int weekday = d.get(Calendar.DAY_OF_WEEK); // get first day of week (Sunday in the U.S.) int firstDayOfWeek = d.getFirstDayOfWeek(); // determine the required indentation for the first line int indent = 0; while (weekday != firstDayOfWeek) { indent++;//w w w. j a v a 2s .co m d.add(Calendar.DAY_OF_MONTH, -1); weekday = d.get(Calendar.DAY_OF_WEEK); } // print weekday names String[] weekdayNames = new DateFormatSymbols().getShortWeekdays(); do { System.out.printf("%4s", weekdayNames[weekday]); d.add(Calendar.DAY_OF_MONTH, 1); weekday = d.get(Calendar.DAY_OF_WEEK); } while (weekday != firstDayOfWeek); System.out.println(); for (int i = 1; i <= indent; i++) System.out.print(" "); d.set(Calendar.DAY_OF_MONTH, 1); do { // print day int day = d.get(Calendar.DAY_OF_MONTH); System.out.printf("%3d", day); // mark current day with * if (day == today) System.out.print("*"); else System.out.print(" "); // advance d to the next day d.add(Calendar.DAY_OF_MONTH, 1); weekday = d.get(Calendar.DAY_OF_WEEK); // start a new line at the start of the week if (weekday == firstDayOfWeek) System.out.println(); } while (d.get(Calendar.MONTH) == month); // the loop exits when d is day 1 of the next month // print final end of line if necessary if (weekday != firstDayOfWeek) System.out.println(); }
From source file:RelativeDateFormat.java
/** * Some test code./* www . j av a 2 s . co m*/ * * @param args ignored. */ public static void main(String[] args) { GregorianCalendar c0 = new GregorianCalendar(2006, 10, 1, 0, 0, 0); GregorianCalendar c1 = new GregorianCalendar(2006, 10, 1, 11, 37, 43); c1.set(Calendar.MILLISECOND, 123); System.out.println("Default: "); RelativeDateFormat rdf = new RelativeDateFormat(c0.getTime().getTime()); System.out.println(rdf.format(c1.getTime())); System.out.println(); System.out.println("Hide milliseconds: "); rdf.setSecondFormatter(new DecimalFormat("0")); System.out.println(rdf.format(c1.getTime())); System.out.println(); System.out.println("Show zero day output: "); rdf.setShowZeroDays(true); System.out.println(rdf.format(c1.getTime())); System.out.println(); System.out.println("Alternative suffixes: "); rdf.setShowZeroDays(false); rdf.setDaySuffix(":"); rdf.setHourSuffix(":"); rdf.setMinuteSuffix(":"); rdf.setSecondSuffix(""); System.out.println(rdf.format(c1.getTime())); System.out.println(); }
From source file:au.com.jwatmuff.eventmanager.Main.java
/** * Main method.//from ww w .j av a 2 s. co m */ public static void main(String args[]) { LogUtils.setupUncaughtExceptionHandler(); /* Set timeout for RMI connections - TODO: move to external file */ System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000"); updateRmiHostName(); /* * Set up menu bar for Mac */ System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager"); /* * Set look and feel to 'system' style */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.info("Failed to set system look and feel"); } /* * Set workingDir to a writable folder for storing competitions, settings etc. */ String applicationData = System.getenv("APPDATA"); if (applicationData != null) { workingDir = new File(applicationData, "EventManager"); if (workingDir.exists() || workingDir.mkdirs()) { // redirect logging to writable folder LogUtils.reconfigureFileAppenders("log4j.properties", workingDir); } else { workingDir = new File("."); } } // log version for debugging log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")"); /* * Copy license if necessary */ File license1 = new File("license.lic"); File license2 = new File(workingDir, "license.lic"); if (license1.exists() && !license2.exists()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } if (license1.exists() && license2.exists()) { if (license1.lastModified() > license2.lastModified()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } } /* * Check if run lock exists, if so ask user if it is ok to continue */ if (!obtainRunLock(false)) { int response = JOptionPane.showConfirmDialog(null, "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?", "Run-lock detected", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) obtainRunLock(true); else System.exit(0); } try { LoadWindow loadWindow = new LoadWindow(); loadWindow.setVisible(true); loadWindow.addMessage("Reading settings.."); /* * Read properties from file */ final Properties props = new Properties(); try { Properties defaultProps = PropertiesLoaderUtils .loadProperties(new ClassPathResource("eventmanager.properties")); props.putAll(defaultProps); } catch (IOException ex) { log.error(ex); } props.putAll(System.getProperties()); File databaseStore = new File(workingDir, "comps"); int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port")); loadWindow.addMessage("Loading Peer Manager.."); log.info("Loading Peer Manager"); ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService(); JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat")); peerManager.addDiscoveryService(manualDiscoveryService); monitorNetworkInterfaceChanges(peerManager); loadWindow.addMessage("Loading Database Manager.."); log.info("Loading Database Manager"); DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager); LicenseManager licenseManager = new LicenseManager(workingDir); loadWindow.addMessage("Loading Load Competition Dialog.."); log.info("Loading Load Competition Dialog"); LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager, peerManager); loadCompetitionWindow.setTitle(WINDOW_TITLE); loadWindow.dispose(); log.info("Starting Load Competition Dialog"); while (true) { // reset permission checker to use our license licenseManager.updatePermissionChecker(); GUIUtils.runModalJFrame(loadCompetitionWindow); if (loadCompetitionWindow.getSuccess()) { DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo(); if (!databaseManager.checkLock(info.id)) { String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n" + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n" + "3) Delete the competition from this computer\n" + "4) If possible, reload this competition from another computer on the network\n" + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked."; String title = "WARNING: Potential Data Corruption Detected"; int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)"); if (status == 0) continue; // return to load competition window } SynchronizingWindow syncWindow = new SynchronizingWindow(); syncWindow.setVisible(true); long t = System.nanoTime(); DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash); long dt = System.nanoTime() - t; log.debug(String.format("Initial sync in %dms", TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS))); syncWindow.dispose(); if (loadCompetitionWindow.isNewDatabase()) { GregorianCalendar calendar = new GregorianCalendar(); Date today = calendar.getTime(); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DAY_OF_MONTH, 31); Date endOfYear = new java.sql.Date(calendar.getTimeInMillis()); CompetitionInfo ci = new CompetitionInfo(); ci.setName(info.name); ci.setStartDate(today); ci.setEndDate(today); ci.setAgeThresholdDate(endOfYear); //ci.setPasswordHash(info.passwordHash); License license = licenseManager.getLicense(); if (license != null) { ci.setLicenseName(license.getName()); ci.setLicenseType(license.getType().toString()); ci.setLicenseContact(license.getContactPhoneNumber()); } database.add(ci); } // Set PermissionChecker to use database's license type String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType(); PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType)); TransactionNotifier notifier = new TransactionNotifier(); database.setListener(notifier); MainWindow mainWindow = new MainWindow(); mainWindow.setDatabase(database); mainWindow.setNotifier(notifier); mainWindow.setPeerManager(peerManager); mainWindow.setLicenseManager(licenseManager); mainWindow.setManualDiscoveryService(manualDiscoveryService); mainWindow.setTitle(WINDOW_TITLE); mainWindow.afterPropertiesSet(); TestUtil.setActivatedDatabase(database); // show main window (modally) GUIUtils.runModalJFrame(mainWindow); // shutdown procedures // System.exit(); database.shutdown(); databaseManager.deactivateDatabase(1500); if (mainWindow.getDeleteOnExit()) { for (File file : info.localDirectory.listFiles()) if (!file.isDirectory()) file.delete(); info.localDirectory.deleteOnExit(); } } else { // This can cause an RuntimeException - Peer is disconnected peerManager.stop(); System.exit(0); } } } catch (Throwable e) { log.error("Error in main function", e); String message = e.getMessage(); if (message == null) message = ""; if (message.length() > 100) message = message.substring(0, 97) + "..."; GUIUtils.displayError(null, "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message); System.exit(0); } }
From source file:Main.java
public final static Timestamp getTodayMidnight() { GregorianCalendar calendar = new GregorianCalendar(); calendar.set(GregorianCalendar.HOUR_OF_DAY, 0); calendar.set(GregorianCalendar.MINUTE, 0); calendar.set(GregorianCalendar.SECOND, 0); calendar.set(GregorianCalendar.MILLISECOND, 0); return new Timestamp(calendar.getTimeInMillis()); }
From source file:Main.java
/** * Remove the time of a date value/*from w w w . j av a2 s. c o m*/ * * @param date Date to remove the time part * @return A date with its time set to 00:00:00 */ public static Date removeTime(Date date) { GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); gc.set(Calendar.HOUR_OF_DAY, 0); gc.set(Calendar.MINUTE, 0); gc.set(Calendar.SECOND, 0); gc.set(Calendar.MILLISECOND, 0); return gc.getTime(); }
From source file:Main.java
/** * Reset the time of a date/*from www . ja v a2 s . co m*/ * @param date the date with time to reset * @return the 0 time date. */ public static Date zeroTimeDate(Date date) { final GregorianCalendar gregorianCalendar = new GregorianCalendar(); gregorianCalendar.setTime(date); gregorianCalendar.set(Calendar.HOUR_OF_DAY, 0); gregorianCalendar.set(Calendar.MINUTE, 0); gregorianCalendar.set(Calendar.SECOND, 0); gregorianCalendar.set(Calendar.MILLISECOND, 0); return gregorianCalendar.getTime(); }
From source file:de.escoand.readdaily.ReminderHandler.java
public static void startReminder(final Context context, final int hour, final int minute) { Intent intent = new Intent(context, ReminderHandler.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE); GregorianCalendar cal = new GregorianCalendar(); // get next reminder cal.set(Calendar.HOUR_OF_DAY, hour); cal.set(Calendar.MINUTE, minute); cal.set(Calendar.SECOND, 0);/*from w w w. j av a 2 s . c o m*/ cal.set(Calendar.MILLISECOND, 0); if (cal.before(Calendar.getInstance())) cal.add(Calendar.DATE, 1); am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent); LogHandler.log(Log.WARN, "activated " + hour + ":" + minute); }
From source file:com.autentia.common.util.DateFormater.java
public static Date normalizeInitDate(Date date) { GregorianCalendar gCalendar = new GregorianCalendar(); gCalendar.setTime(date);//from w w w .j a v a2 s.c o m gCalendar.set(Calendar.HOUR_OF_DAY, 0); gCalendar.set(Calendar.MINUTE, 0); gCalendar.set(Calendar.SECOND, 0); gCalendar.set(Calendar.MILLISECOND, 0); return gCalendar.getTime(); }
From source file:com.autentia.common.util.DateFormater.java
public static Date normalizeEndDate(Date date) { GregorianCalendar gCalendar = new GregorianCalendar(); gCalendar.setTime(date);// w w w.j a v a 2s .c om gCalendar.set(Calendar.HOUR_OF_DAY, 23); gCalendar.set(Calendar.MINUTE, 59); gCalendar.set(Calendar.SECOND, 59); gCalendar.set(Calendar.MILLISECOND, 999); return gCalendar.getTime(); }
From source file:com.jmstudios.redmoon.receiver.AutomaticFilterChangeReceiver.java
public static void scheduleNextAlarm(Context context, String time, Intent operation) { GregorianCalendar calendar = new GregorianCalendar(); calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0])); calendar.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1])); GregorianCalendar now = new GregorianCalendar(); now.add(Calendar.SECOND, 1);// ww w.j ava 2 s . co m if (calendar.before(now)) { calendar.add(Calendar.DATE, 1); } if (DEBUG) Log.i(TAG, "Scheduling alarm for " + calendar.toString()); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, operation, 0); if (android.os.Build.VERSION.SDK_INT >= 19) { alarmManager.setExact(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); } else { alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent); } }