List of usage examples for java.util Calendar ZONE_OFFSET
int ZONE_OFFSET
To view the source code for java.util Calendar ZONE_OFFSET.
Click Source Link
get
and set
indicating the raw offset from GMT in milliseconds. From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Format dates as specified in rfc3339 (required for Atom dates) * //from w ww . j a va2 s .com * @param d the Date to be formatted * @return the formatted date * @should not fail given a null date * @should convert date to rfc */ public static String dateToRFC3339(Date d) { if (d == null) return null; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(RFC_3339_DATE_FORMAT); Calendar cal = new GregorianCalendar(); cal.setTime(d); cal.setTimeZone(TimeZone.getDefault()); simpleDateFormat.setCalendar(cal); StringBuilder result = new StringBuilder(simpleDateFormat.format(d)); int offset_millis = cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET); int offset_hours = Math.abs(offset_millis / (1000 * 60 * 60)); int offset_minutes = Math.abs((offset_millis / (1000 * 60)) % 60); if (offset_millis == 0) { result.append("Z"); } else { result.append((offset_millis > 0) ? "+" : "-").append(doubleDigit.format(offset_hours)).append(":") .append(doubleDigit.format(offset_minutes)); } return result.toString(); }
From source file:com.zimbra.cs.imap.ImapRequest.java
Date readDate(boolean datetime, boolean checkRange) throws ImapParseException { String dateStr = (peekChar() == '"' ? readQuoted() : readAtom()); if (dateStr.length() < (datetime ? 26 : 10)) { throw new ImapParseException(tag, "invalid date format"); }/*from ww w .j a v a 2 s .c o m*/ Calendar cal = new GregorianCalendar(); cal.clear(); int pos = 0, count; if (datetime && dateStr.charAt(0) == ' ') { pos++; } count = 2 - pos - (datetime || dateStr.charAt(1) != '-' ? 0 : 1); validateDigits(dateStr, pos, count, cal, Calendar.DAY_OF_MONTH); pos += count; validateChar(dateStr, pos, '-'); pos++; validateMonth(dateStr, pos, cal); pos += 3; validateChar(dateStr, pos, '-'); pos++; validateDigits(dateStr, pos, 4, cal, Calendar.YEAR); pos += 4; if (datetime) { validateChar(dateStr, pos, ' '); pos++; validateDigits(dateStr, pos, 2, cal, Calendar.HOUR); pos += 2; validateChar(dateStr, pos, ':'); pos++; validateDigits(dateStr, pos, 2, cal, Calendar.MINUTE); pos += 2; validateChar(dateStr, pos, ':'); pos++; validateDigits(dateStr, pos, 2, cal, Calendar.SECOND); pos += 2; validateChar(dateStr, pos, ' '); pos++; boolean zonesign = dateStr.charAt(pos) == '+'; validateChar(dateStr, pos, zonesign ? '+' : '-'); pos++; int zonehrs = validateDigits(dateStr, pos, 2, cal, -1); pos += 2; int zonemins = validateDigits(dateStr, pos, 2, cal, -1); pos += 2; cal.set(Calendar.ZONE_OFFSET, (zonesign ? 1 : -1) * (60 * zonehrs + zonemins) * 60000); cal.set(Calendar.DST_OFFSET, 0); } if (pos != dateStr.length()) { throw new ImapParseException(tag, "excess characters at end of date string"); } Date date = cal.getTime(); if (checkRange && date.getTime() < 0) { throw new ImapParseException(tag, "date out of range"); } return date; }
From source file:processing.app.debug.Compiler.java
private PreferencesMap createBuildPreferences(String _buildPath, String _primaryClassName) throws RunnerException { if (BaseNoGui.getBoardPreferences() == null) { RunnerException re = new RunnerException( _("No board selected; please choose a board from the Tools > Board menu.")); re.hideStackTrace();// www. jav a2s . com throw re; } // Check if the board needs a platform from another package TargetPlatform targetPlatform = BaseNoGui.getTargetPlatform(); TargetPlatform corePlatform = null; PreferencesMap boardPreferences = BaseNoGui.getBoardPreferences(); String core = boardPreferences.get("build.core", "arduino"); if (core.contains(":")) { String[] split = core.split(":"); core = split[1]; corePlatform = BaseNoGui.getTargetPlatform(split[0], targetPlatform.getId()); if (corePlatform == null) { RunnerException re = new RunnerException( I18n.format(_("Selected board depends on '{0}' core (not installed)."), split[0])); re.hideStackTrace(); throw re; } } // Merge all the global preference configuration in order of priority PreferencesMap buildPref = new PreferencesMap(); buildPref.putAll(PreferencesData.getMap()); if (corePlatform != null) { buildPref.putAll(corePlatform.getPreferences()); } buildPref.putAll(targetPlatform.getPreferences()); buildPref.putAll(BaseNoGui.getBoardPreferences()); for (String k : buildPref.keySet()) { if (buildPref.get(k) == null) { buildPref.put(k, ""); } } buildPref.put("build.path", _buildPath); buildPref.put("build.project_name", _primaryClassName); buildPref.put("build.arch", targetPlatform.getId().toUpperCase()); // Platform.txt should define its own compiler.path. For // compatibility with earlier 1.5 versions, we define a (ugly, // avr-specific) default for it, but this should be removed at some // point. if (!buildPref.containsKey("compiler.path")) { System.err.println(_( "Third-party platform.txt does not define compiler.path. Please report this to the third-party hardware maintainer.")); buildPref.put("compiler.path", BaseNoGui.getAvrBasePath()); } TargetPlatform referencePlatform = null; if (corePlatform != null) { referencePlatform = corePlatform; } else { referencePlatform = targetPlatform; } buildPref.put("build.platform.path", referencePlatform.getFolder().getAbsolutePath()); // Core folder File coreFolder = new File(referencePlatform.getFolder(), "cores"); coreFolder = new File(coreFolder, core); buildPref.put("build.core", core); buildPref.put("build.core.path", coreFolder.getAbsolutePath()); // System Folder File systemFolder = referencePlatform.getFolder(); systemFolder = new File(systemFolder, "system"); buildPref.put("build.system.path", systemFolder.getAbsolutePath()); // Variant Folder String variant = buildPref.get("build.variant"); if (variant != null) { TargetPlatform t; if (!variant.contains(":")) { t = targetPlatform; } else { String[] split = variant.split(":", 2); t = BaseNoGui.getTargetPlatform(split[0], targetPlatform.getId()); variant = split[1]; } File variantFolder = new File(t.getFolder(), "variants"); variantFolder = new File(variantFolder, variant); buildPref.put("build.variant.path", variantFolder.getAbsolutePath()); } else { buildPref.put("build.variant.path", ""); } ContributedPlatform installedPlatform = BaseNoGui.indexer .getInstalled(referencePlatform.getContainerPackage().getId(), referencePlatform.getId()); if (installedPlatform != null) { List<ContributedTool> tools = installedPlatform.getResolvedTools(); BaseNoGui.createToolPreferences(tools, false); } // Build Time GregorianCalendar cal = new GregorianCalendar(); long current = new Date().getTime() / 1000; long timezone = cal.get(Calendar.ZONE_OFFSET) / 1000; long daylight = cal.get(Calendar.DST_OFFSET) / 1000; buildPref.put("extra.time.utc", Long.toString(current)); buildPref.put("extra.time.local", Long.toString(current + timezone + daylight)); buildPref.put("extra.time.zone", Long.toString(timezone)); buildPref.put("extra.time.dst", Long.toString(daylight)); List<Map.Entry<String, String>> unsetPrefs = buildPref.entrySet().stream() .filter(entry -> Constants.PREF_REMOVE_PLACEHOLDER.equals(entry.getValue())) .collect(Collectors.toList()); buildPref.entrySet().stream().filter(entry -> { return unsetPrefs.stream().filter(unsetPrefEntry -> entry.getValue().contains(unsetPrefEntry.getKey())) .count() > 0; }).forEach(invalidEntry -> buildPref.put(invalidEntry.getKey(), "")); return buildPref; }
From source file:processing.app.debug.OldCompiler.java
private PreferencesMap createBuildPreferences(String _buildPath, String _primaryClassName) throws RunnerException { if (BaseNoGui.getBoardPreferences() == null) { RunnerException re = new RunnerException( tr("No board selected; please choose a board from the Tools > Board menu.")); re.hideStackTrace();/*from ww w. java 2 s . c o m*/ throw re; } // Check if the board needs a platform from another package TargetPlatform targetPlatform = BaseNoGui.getTargetPlatform(); TargetPlatform corePlatform = null; PreferencesMap boardPreferences = BaseNoGui.getBoardPreferences(); String core = boardPreferences.get("build.core", "arduino"); if (core.contains(":")) { String[] split = core.split(":"); core = split[1]; corePlatform = BaseNoGui.getTargetPlatform(split[0], targetPlatform.getId()); if (corePlatform == null) { RunnerException re = new RunnerException( I18n.format(tr("Selected board depends on '{0}' core (not installed)."), split[0])); re.hideStackTrace(); throw re; } } // Merge all the global preference configuration in order of priority PreferencesMap buildPref = new PreferencesMap(); buildPref.putAll(PreferencesData.getMap()); if (corePlatform != null) { buildPref.putAll(corePlatform.getPreferences()); } buildPref.putAll(targetPlatform.getPreferences()); buildPref.putAll(BaseNoGui.getBoardPreferences()); for (String k : buildPref.keySet()) { if (buildPref.get(k) == null) { buildPref.put(k, ""); } } buildPref.put("build.path", _buildPath); buildPref.put("build.project_name", _primaryClassName); buildPref.put("build.arch", targetPlatform.getId().toUpperCase()); // Platform.txt should define its own compiler.path. For // compatibility with earlier 1.5 versions, we define a (ugly, // avr-specific) default for it, but this should be removed at some // point. if (!buildPref.containsKey("compiler.path")) { System.err.println(tr( "Third-party platform.txt does not define compiler.path. Please report this to the third-party hardware maintainer.")); buildPref.put("compiler.path", BaseNoGui.getAvrBasePath()); } TargetPlatform referencePlatform = null; if (corePlatform != null) { referencePlatform = corePlatform; } else { referencePlatform = targetPlatform; } buildPref.put("build.platform.path", referencePlatform.getFolder().getAbsolutePath()); // Core folder File coreFolder = new File(referencePlatform.getFolder(), "cores"); coreFolder = new File(coreFolder, core); buildPref.put("build.core", core); buildPref.put("build.core.path", coreFolder.getAbsolutePath()); // System Folder File systemFolder = referencePlatform.getFolder(); systemFolder = new File(systemFolder, "system"); buildPref.put("build.system.path", systemFolder.getAbsolutePath()); // Variant Folder String variant = buildPref.get("build.variant"); if (variant != null) { TargetPlatform t; if (!variant.contains(":")) { t = targetPlatform; } else { String[] split = variant.split(":", 2); t = BaseNoGui.getTargetPlatform(split[0], targetPlatform.getId()); variant = split[1]; } File variantFolder = new File(t.getFolder(), "variants"); variantFolder = new File(variantFolder, variant); buildPref.put("build.variant.path", variantFolder.getAbsolutePath()); } else { buildPref.put("build.variant.path", ""); } ContributedPlatform installedPlatform = BaseNoGui.indexer .getInstalled(referencePlatform.getContainerPackage().getId(), referencePlatform.getId()); if (installedPlatform != null) { List<ContributedTool> tools = installedPlatform.getResolvedTools(); BaseNoGui.createToolPreferences(tools, false); } // Build Time GregorianCalendar cal = new GregorianCalendar(); long current = new Date().getTime() / 1000; long timezone = cal.get(Calendar.ZONE_OFFSET) / 1000; long daylight = cal.get(Calendar.DST_OFFSET) / 1000; buildPref.put("extra.time.utc", Long.toString(current)); buildPref.put("extra.time.local", Long.toString(current + timezone + daylight)); buildPref.put("extra.time.zone", Long.toString(timezone)); buildPref.put("extra.time.dst", Long.toString(daylight)); List<Map.Entry<String, String>> unsetPrefs = buildPref.entrySet().stream() .filter(entry -> Constants.PREF_REMOVE_PLACEHOLDER.equals(entry.getValue())) .collect(Collectors.toList()); buildPref.entrySet().stream() .filter(entry -> unsetPrefs.stream() .filter(unsetPrefEntry -> entry.getValue().contains(unsetPrefEntry.getKey())).count() > 0) .forEach(invalidEntry -> buildPref.put(invalidEntry.getKey(), "")); new LoadVIDPIDSpecificPreferences().load(buildPref); return buildPref; }
From source file:xc.mst.manager.record.DefaultRecordService.java
@Override public long getCount(Date fromDate, Date untilDate, Set set, int formatId, int serviceId) throws IndexException { Date from; // fromDate, or the minimum value for a Date if fromDate is null Date until; // toDate, or now if toDate is null // If from is null, set it to the minimum possible value // Otherwise set it to the same value as fromDate if (fromDate == null) { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date(0)); c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) - ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / (60 * 60 * 1000))); from = c.getTime();//from w w w . j a v a 2 s . c om } else { from = fromDate; } // If to is null, set it to now // Otherwise set it to the same value as toDate if (untilDate == null) { GregorianCalendar c = new GregorianCalendar(); c.setTime(new Date()); c.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY) - ((c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)) / (60 * 60 * 1000))); until = c.getTime(); } else { until = untilDate; } // True if we're getting the count for a specific set, false if we're getting it for all records boolean useSet = (set != null); // True if we're getting the count for a specific metadataPrefix, false if we're getting it for all records boolean useMetadataPrefix = (formatId > 0); DateFormat format = DateFormat.getInstance(); if (log.isDebugEnabled()) log.debug("Counting the records updated later than " + format.format(from) + " and earlier than " + format.format(until) + (useSet ? " with set ID " + set.getSetSpec() : "") + (useMetadataPrefix ? " with format ID " + formatId : "")); // Create a query to get the Documents for unprocessed records SolrQuery query = new SolrQuery(); StringBuffer queryBuffer = new StringBuffer(); queryBuffer.append(FIELD_SERVICE_ID).append(":").append(Integer.toString(serviceId)); if (useSet) queryBuffer.append(" AND ").append(FIELD_SET_SPEC).append(":").append(set.getSetSpec()); if (useMetadataPrefix) queryBuffer.append(" AND ").append(FIELD_FORMAT_ID).append(":").append(Integer.toString(formatId)); queryBuffer.append(" AND ").append(FIELD_DELETED).append(":").append("false"); query.setQuery(queryBuffer.toString()); if (from != null && until != null) query.addFilterQuery( FIELD_UPDATED_AT + ":[" + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(from)) + " TO " + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").format(until)) + "]"); // Get the result of the query RecordList records = new RecordList(query, 0); if (log.isDebugEnabled()) log.debug("Found " + records.size() + " records updated later than " + format.format(from) + " and earlier than " + format.format(until) + (useSet ? " with set ID " + set.getSetSpec() : "") + (useMetadataPrefix ? " with format ID " + formatId : "")); // Return the list of results return records.size(); }
From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java
/** * Gets the timezone offset from UTC to local time for the given time * (including DST)./*from ww w . j a va2s . c om*/ */ private long getToLocalTimeZoneOffset(long time) { Calendar c = getCalendar(); c.setTimeInMillis(time); return ((long) c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)); }
From source file:com.healthmarketscience.jackcess.impl.ColumnImpl.java
/** * Gets the timezone offset from local time to UTC for the given time * (including DST).//from w ww .jav a 2 s. c o m */ private long getFromLocalTimeZoneOffset(long time) { // getting from local time back to UTC is a little wonky (and not // guaranteed to get you back to where you started) Calendar c = getCalendar(); c.setTimeInMillis(time); // apply the zone offset first to get us closer to the original time c.setTimeInMillis(time - c.get(Calendar.ZONE_OFFSET)); return ((long) c.get(Calendar.ZONE_OFFSET) + c.get(Calendar.DST_OFFSET)); }
From source file:com.aurel.track.lucene.LuceneUtil.java
/** * Typically the value itself converted to string * But there are some exceptions where the toString() * doesn't work as expected. //from ww w . j a v a 2 s. com * It should be implemented * specific to the lucene requirement to be indexable * set the date according to offset from the GMT * see http://www.gossamer-threads.com/lists/lucene/java-user/39303?search_string=DateTools;#39303 * @param value * @return */ public static String getLuceneDateValue(Object value) { Calendar cal = new GregorianCalendar(); int minutesOffset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000); if (value != null) { Date dateValue = null; try { dateValue = (Date) value; } catch (Exception e) { LOGGER.error("The type of the lucene value is " + value.getClass().getName() + ". Casting it to Date failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } if (dateValue != null) { cal.setTime(dateValue); cal.add(Calendar.MINUTE, minutesOffset); return DateTools.dateToString(cal.getTime(), DateTools.Resolution.DAY); } } return null; }
From source file:org.apache.axis2.databinding.utils.ConverterUtil.java
/** * Code from Axis1 code base Note - We only follow the convention in the latest schema spec * * @param source// ww w .ja va2 s. co m * @return Returns Calendar. */ public static Calendar convertToDateTime(String source) { if ((source == null) || source.trim().equals("")) { return null; } source = source.trim(); // the lexical representation of the date time as follows // '-'? yyyy '-' mm '-' dd 'T' hh ':' mm ':' ss ('.' s+)? (zzzzzz)? Date date = null; Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.setLenient(false); if (source.startsWith("-")) { source = source.substring(1); calendar.set(Calendar.ERA, GregorianCalendar.BC); } int year = 0; int month = 0; int day = 0; int hour = 0; int minite = 0; int second = 0; long miliSecond = 0; int timeZoneOffSet = TimeZone.getDefault().getRawOffset(); if ((source != null) && (source.length() >= 19)) { if ((source.charAt(4) != '-') || (source.charAt(7) != '-') || (source.charAt(10) != 'T') || (source.charAt(13) != ':') || (source.charAt(16) != ':')) { throw new RuntimeException("invalid date format (" + source + ") with out - s at correct place "); } year = Integer.parseInt(source.substring(0, 4)); month = Integer.parseInt(source.substring(5, 7)); day = Integer.parseInt(source.substring(8, 10)); hour = Integer.parseInt(source.substring(11, 13)); minite = Integer.parseInt(source.substring(14, 16)); second = Integer.parseInt(source.substring(17, 19)); int milliSecondPartLength = 0; if (source.length() > 19) { String rest = source.substring(19); if (rest.startsWith(".")) { // i.e this have the ('.'s+) part if (rest.endsWith("Z")) { // this is in gmt time zone timeZoneOffSet = 0; calendar.setTimeZone(TimeZone.getTimeZone("GMT")); miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("Z"))); milliSecondPartLength = rest.substring(1, rest.lastIndexOf("Z")).trim().length(); } else if ((rest.lastIndexOf("+") > 0) || (rest.lastIndexOf("-") > 0)) { // this is given in a general time zione String timeOffSet = null; if (rest.lastIndexOf("+") > 0) { timeOffSet = rest.substring(rest.lastIndexOf("+") + 1); miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("+"))); milliSecondPartLength = rest.substring(1, rest.lastIndexOf("+")).trim().length(); // we keep +1 or -1 to finally calculate the value timeZoneOffSet = 1; } else if (rest.lastIndexOf("-") > 0) { timeOffSet = rest.substring(rest.lastIndexOf("-") + 1); miliSecond = Integer.parseInt(rest.substring(1, rest.lastIndexOf("-"))); milliSecondPartLength = rest.substring(1, rest.lastIndexOf("-")).trim().length(); // we keep +1 or -1 to finally calculate the value timeZoneOffSet = -1; } if (timeOffSet.charAt(2) != ':') { throw new RuntimeException( "invalid time zone format (" + source + ") without : at correct place"); } int hours = Integer.parseInt(timeOffSet.substring(0, 2)); int minits = Integer.parseInt(timeOffSet.substring(3, 5)); timeZoneOffSet = ((hours * 60) + minits) * 60000 * timeZoneOffSet; } else { // i.e it does not have time zone miliSecond = Integer.parseInt(rest.substring(1)); milliSecondPartLength = rest.substring(1).trim().length(); } } else { if (rest.startsWith("Z")) { calendar.setTimeZone(TimeZone.getTimeZone("GMT")); // this is in gmt time zone timeZoneOffSet = 0; } else if (rest.startsWith("+") || rest.startsWith("-")) { // this is given in a general time zione if (rest.charAt(3) != ':') { throw new RuntimeException( "invalid time zone format (" + source + ") without : at correct place"); } int hours = Integer.parseInt(rest.substring(1, 3)); int minits = Integer.parseInt(rest.substring(4, 6)); timeZoneOffSet = ((hours * 60) + minits) * 60000; if (rest.startsWith("-")) { timeZoneOffSet = timeZoneOffSet * -1; } } else { throw new NumberFormatException("in valid time zone attribute"); } } } calendar.set(Calendar.YEAR, year); // xml month is started from 1 and calendar month is started from 0 calendar.set(Calendar.MONTH, month - 1); calendar.set(Calendar.DAY_OF_MONTH, day); calendar.set(Calendar.HOUR_OF_DAY, hour); calendar.set(Calendar.MINUTE, minite); calendar.set(Calendar.SECOND, second); if (milliSecondPartLength != 3) { // milisecond part represenst the fraction of the second so we have to // find the fraction and multiply it by 1000. So if milisecond part // has three digits nothing required miliSecond = miliSecond * 1000; for (int i = 0; i < milliSecondPartLength; i++) { miliSecond = miliSecond / 10; } } calendar.set(Calendar.MILLISECOND, (int) miliSecond); calendar.set(Calendar.ZONE_OFFSET, timeZoneOffSet); // set the day light offset only if the time zone is present if (source.length() > 19) { calendar.set(Calendar.DST_OFFSET, 0); } } else { throw new NumberFormatException("date string can not be less than 19 characters"); } return calendar; }
From source file:com.aurel.track.lucene.search.LuceneSearcher.java
/** * Transforms the user entered date string to lucene date string format * by trying to reconstruct the Date object either by local or by ISO (yyy-MM-dd) * DateTools calculates in GMT (comparing to the server TimeZone), so it should be adjusted * @param originalFieldValue/*from w w w . j a va2s . co m*/ * @param locale * @return */ private static String transformDateFields(String originalFieldValue, Locale locale) { String dateString = originalFieldValue; Date date; //DateTimeUtils dtu = new DateTimeUtils(locale); date = DateTimeUtils.getInstance().parseGUIDate(originalFieldValue, locale); if (date == null) { date = DateTimeUtils.getInstance().parseShortDate(originalFieldValue, locale); } //set the date according to offset from the GMT //see http://www.gossamer-threads.com/lists/lucene/java-user/39303?search_string=DateTools;#39303 Calendar cal = new GregorianCalendar(); int minutesOffset = (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)) / (60 * 1000); if (date != null) { cal.setTime(date); cal.add(Calendar.MINUTE, minutesOffset); return DateTools.dateToString(cal.getTime(), Resolution.DAY); } date = DateTimeUtils.getInstance().parseISODate(originalFieldValue); if (date != null) { cal.setTime(date); cal.add(Calendar.MINUTE, minutesOffset); return DateTools.dateToString(cal.getTime(), Resolution.DAY); } return dateString; }