Example usage for java.util Calendar setTimeZone

List of usage examples for java.util Calendar setTimeZone

Introduction

In this page you can find the example usage for java.util Calendar setTimeZone.

Prototype

public void setTimeZone(TimeZone value) 

Source Link

Document

Sets the time zone with the given time zone value.

Usage

From source file:com.orange.oidc.tim.service.TokensKeys.java

boolean isRefreshTokenValid() {
    // return isTokenValid(refresh_token);
    //[NBAN] TODO verification de l'expiration  partir de la chaine de caractre et non le timems qui n'est pas set dans le cas du SDStorage
    if ((timems == 0) && (this.expires != null)) {
        Calendar cal = fromStringToDate(this.expires);
        return cal.after(Calendar.getInstance());
    } else if (timems != 0) {
        Calendar calNow = Calendar.getInstance();
        calNow.setTimeZone(TimeZone.getTimeZone("GMT"));
        long now = calNow.getTimeInMillis();
        return timems > now;
    }//from   ww w. java 2 s.  c  o  m
    return false;
}

From source file:org.pentaho.reporting.engine.classic.core.modules.gui.base.parameters.DatePickerParameterComponent.java

/**
 * Constructs a new <code>DatePickerParameterComponent</code>.
 *
 * @param entry//  www . ja v a2 s .com
 *          the parameter-definition for which we create an input component.
 * @param updateContext
 *          the update context, which resyncs parameters on changes.
 */
public DatePickerParameterComponent(final ParameterDefinitionEntry entry,
        final ParameterContext parameterContext, final ParameterUpdateContext updateContext) {
    this.parameterName = entry.getName();
    this.updateContext = updateContext;
    this.dateType = entry.getValueType();
    if (this.dateType.isArray()) {
        this.dateType = this.dateType.getComponentType();
    }

    String formatString = entry.getTranslatedParameterAttribute(ParameterAttributeNames.Core.NAMESPACE,
            ParameterAttributeNames.Core.DATA_FORMAT, parameterContext);

    final String timeZoneSpec = entry.getParameterAttribute(ParameterAttributeNames.Core.NAMESPACE,
            ParameterAttributeNames.Core.TIMEZONE, parameterContext);
    final Locale locale = parameterContext.getResourceBundleFactory().getLocale();
    final TimeZone timeZone = TextComponentEditHandler.createTimeZone(timeZoneSpec,
            parameterContext.getResourceBundleFactory().getTimeZone());

    sdf = createDateFormat(formatString, locale, timeZone);

    final Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(timeZone);

    dateChooserPanel = new DateChooserPanel(calendar, true);
    dateChooserPanel.addPropertyChangeListener(DateChooserPanel.PROPERTY_DATE, new InternalDateUpdateHandler());

    dateField = new JTextField();
    dateField.setColumns(20);

    final TextComponentEditHandler listener = new TextComponentEditHandler(entry.getValueType(),
            entry.getName(), dateField, updateContext, sdf);
    dateField.getDocument().addDocumentListener(listener);
    dateField.addActionListener(listener);

    setLayout(new BorderLayout());
    dateField.setEditable(true);

    pickDateButton = new JButton(new PickDateListener());

    final JPanel datePanel = new JPanel(new FlowLayout());
    datePanel.add(dateField);
    datePanel.add(pickDateButton);
    add(datePanel, BorderLayout.WEST);

    this.updateContext.addChangeListener(new DateUpdateHandler(parameterName));
}

From source file:com.zimbra.cs.fb.ExchangeMessage.java

protected long millisToMonths(long millis) {
    // number of freebusy months = year * 16 + month
    // why * 16 not * 12, ask msft.
    Calendar c = new GregorianCalendar();
    c.setTimeZone(ICalTimeZone.getUTC());
    c.setTime(new Date(millis));
    return c.get(Calendar.YEAR) * 16 + c.get(Calendar.MONTH) + 1; // january is 0
}

From source file:com.zimbra.cs.fb.ExchangeMessage.java

private int millisToMinutes(long millis) {
    // millis since epoch to minutes since 1st of the month
    Calendar c = new GregorianCalendar();
    c.setTimeZone(ICalTimeZone.getUTC());
    c.setTime(new Date(millis));
    int days = c.get(Calendar.DAY_OF_MONTH) - 1;
    int hours = 24 * days + c.get(Calendar.HOUR_OF_DAY);
    int minutes = c.get(Calendar.MINUTE);
    return 60 * hours + minutes;
}

From source file:microsoft.exchange.webservices.data.property.complex.TimeChange.java

/**
 * Tries to read element from XML./*from  w  w w.  j a v  a  2 s . c o  m*/
 *
 * @param reader accepts EwsServiceXmlReader
 * @return True if element was read
 * @throws Exception throws Exception
 */
@Override
public boolean tryReadElementFromXml(EwsServiceXmlReader reader) throws Exception {

    if (reader.getLocalName().equalsIgnoreCase(XmlElementNames.Offset)) {
        this.offset = EwsUtilities.getXSDurationToTimeSpan(reader.readElementValue());
        return true;
    } else if (reader.getLocalName().equalsIgnoreCase(XmlElementNames.RelativeYearlyRecurrence)) {
        this.recurrence = new TimeChangeRecurrence();
        this.recurrence.loadFromXml(reader, reader.getLocalName());
        return true;
    } else if (reader.getLocalName().equalsIgnoreCase(XmlElementNames.AbsoluteDate)) {
        Calendar cal = DatatypeConverter.parseDate(reader.readElementValue());
        cal.setTimeZone(TimeZone.getTimeZone("UTC"));
        this.absoluteDate = cal.getTime();
        return true;
    } else if (reader.getLocalName().equalsIgnoreCase(XmlElementNames.Time)) {
        Calendar cal = DatatypeConverter.parseTime(reader.readElementValue());
        this.time = new Time(cal.getTime());
        return true;
    } else {
        return false;
    }
}

From source file:com.guanyin.userface.ViewPagerActivity.java

private CharSequence getCurDate() {
    String[] week = { "", "", "", "", "", "",
            "" };
    Calendar cd = Calendar.getInstance();
    cd.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
    cd.get(Calendar.YEAR);// w  w w.ja  v  a 2 s  . c o m
    return cd.get(Calendar.YEAR) + "/" + (cd.get(Calendar.MONTH) + 1) + "/" + cd.get(Calendar.DATE)
            + week[cd.get(Calendar.DAY_OF_WEEK) - 1];
}

From source file:at.pagu.soldockr.core.query.CriteriaTest.java

@Test
public void testIsWithJavaDateValue() {
    DateTime dateTime = new DateTime(2012, 8, 21, 6, 35, 0, DateTimeZone.UTC);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
    calendar.setTimeInMillis(dateTime.getMillis());

    Criteria criteria = new Criteria("dateField").is(calendar.getTime());
    Assert.assertEquals("dateField:2012\\-08\\-21T06\\:35\\:00.000Z", criteria.createQueryString());
}

From source file:fr.free.nrw.commons.contributions.Contribution.java

/**
 * Returns upload date in either TEMPLATE_DATE_ACC_TO_EXIF or TEMPLATE_DATA_OTHER_SOURCE
 * @return//  w  ww.  jav  a2 s .  c o m
 */
private String getTemplatizedCreatedDate() {
    if (dateCreated != null) {
        if (UploadableFile.DateTimeWithSource.EXIF_SOURCE.equals(dateCreatedSource)) {
            return String.format(Locale.ENGLISH, TEMPLATE_DATE_ACC_TO_EXIF,
                    DateUtil.getDateStringWithSkeletonPattern(dateCreated, "yyyy-MM-dd")) + "\n";
        } else {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dateCreated);
            calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
            return String.format(Locale.ENGLISH, TEMPLATE_DATA_OTHER_SOURCE, calendar.get(Calendar.YEAR),
                    calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)) + "\n";
        }
    }
    return "";
}

From source file:org.springframework.integration.x.rollover.file.RolloverFileOutputStream.java

/**
 * @param filename/*from   w  ww .j  av  a  2  s .c  om*/
 *            The filename must include the string "yyyy_mm_dd", which is replaced with the actual date when
 *            creating and rolling over the file.
 * @param append
 *            If true, existing files will be appended to.
 * @param zone
 *            the timezone for the output
 * @param dateFormat
 *            The format for the date file substitution. The default is "yyyy_MM_dd".
 * @param rolloverStartTimeMs
 *            Defines the time in [ms] of the first file roll over process to start.
 * @param rolloverPeriodMs
 *            Defines the frequency (in ms) of the file roll over processes.
 * @throws IOException
 *             if unable to create output
 */
public RolloverFileOutputStream(String filename, boolean append, TimeZone zone, String dateFormat,
        long rolloverStartTimeMs, long rolloverPeriodMs, long maxRolledFileSize, String archivePrefix,
        boolean compressArchive, int bufferSize, FileCompressor fileCompressor) throws IOException {

    super(null);

    this.bufferSize = bufferSize;
    this.compressArchive = compressArchive;
    this.archivePrefix = archivePrefix;
    this.maxRolledFileSize = maxRolledFileSize;

    if (dateFormat == null) {
        dateFormat = ROLLOVER_FILE_DATE_FORMAT;
    }

    fileDateFormat = new SimpleDateFormat(dateFormat);

    if (StringUtils.isEmpty(filename)) {
        throw new IllegalArgumentException("Invalid filename");
    }

    filePath = filename.trim();
    fileDir = new File(new File(filename).getAbsolutePath()).getParentFile();

    if (fileDir != null && (!fileDir.isDirectory() || !fileDir.canWrite())) {
        throw new IOException("Cannot write into directory: " + fileDir);
    }

    appendToFile = append;
    setFile(true);

    synchronized (RolloverFileOutputStream.class) {

        if (rolloverTimer == null) {
            rolloverTimer = new Timer(RolloverFileOutputStream.class.getName(), true);
        }

        rollTask = new RollTask();

        Date startTime = null;
        if (rolloverStartTimeMs <= 0) {
            Calendar now = Calendar.getInstance();
            now.setTimeZone(zone);

            GregorianCalendar midnight = new GregorianCalendar(now.get(Calendar.YEAR), now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH), 23, 0);
            midnight.setTimeZone(zone);
            midnight.add(Calendar.HOUR, 1);

            startTime = midnight.getTime();
        } else {
            startTime = new Date(rolloverStartTimeMs);
        }

        long period = (rolloverPeriodMs <= 0) ? 86400000 : rolloverPeriodMs;

        rolloverTimer.scheduleAtFixedRate(rollTask, startTime, period);
    }

    this.fileCompressor = fileCompressor;
}

From source file:org.codehaus.mojo.mrm.impl.maven.FileSystemArtifactStore.java

/**
 * {@inheritDoc}//from w  w  w  .  j  a v  a2 s  .  c o m
 */
public Set<Artifact> getArtifacts(final String groupId, final String artifactId, final String version) {
    Entry parentEntry = backing.get(groupId.replace('.', '/') + "/" + artifactId + "/" + version);
    if (!(parentEntry instanceof DirectoryEntry)) {
        return Collections.emptySet();
    }
    DirectoryEntry parentDir = (DirectoryEntry) parentEntry;
    Entry[] entries = backing.listEntries(parentDir);
    final Pattern rule;

    abstract class ArtifactFactory {
        abstract Artifact get(Entry entry);
    }

    final ArtifactFactory factory;
    if (version.endsWith("-SNAPSHOT")) {
        rule = Pattern.compile("\\Q" + artifactId + "\\E-(?:\\Q" + StringUtils.removeEnd(version, "-SNAPSHOT")
                + "\\E-(SNAPSHOT|(\\d{4})(\\d{2})(\\d{2})\\.(\\d{2})(\\d{2})(\\d{2})-(\\d+)))(?:-([^.]+))?\\.([^/]*)");
        factory = new ArtifactFactory() {
            public Artifact get(Entry entry) {
                Matcher matcher = rule.matcher(entry.getName());
                if (!matcher.matches()) {
                    return null;
                }
                if (matcher.group(1).equals("SNAPSHOT")) {
                    return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10));
                }
                try {
                    Calendar cal = new GregorianCalendar();
                    cal.setTimeZone(TimeZone.getTimeZone("GMT"));
                    cal.set(Calendar.YEAR, Integer.parseInt(matcher.group(2)));
                    cal.set(Calendar.MONTH, Integer.parseInt(matcher.group(3)) - 1);
                    cal.set(Calendar.DAY_OF_MONTH, Integer.parseInt(matcher.group(4)));
                    cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(matcher.group(5)));
                    cal.set(Calendar.MINUTE, Integer.parseInt(matcher.group(6)));
                    cal.set(Calendar.SECOND, Integer.parseInt(matcher.group(7)));
                    long timestamp = cal.getTimeInMillis();
                    int buildNumber = Integer.parseInt(matcher.group(8));
                    return new Artifact(groupId, artifactId, version, matcher.group(9), matcher.group(10),
                            timestamp, buildNumber);
                } catch (NullPointerException e) {
                    return null;
                }
            }
        };
    } else {
        rule = Pattern.compile("\\Q" + artifactId + "\\E-\\Q" + version + "\\E(?:-([^.]+))?\\.(.+)");
        factory = new ArtifactFactory() {
            public Artifact get(Entry entry) {
                Matcher matcher = rule.matcher(entry.getName());
                if (!matcher.matches()) {
                    return null;
                }
                return new Artifact(groupId, artifactId, version, matcher.group(1), matcher.group(2));
            }
        };
    }
    Set<Artifact> result = new HashSet<Artifact>(entries.length);
    for (int i = 0; i < entries.length; i++) {
        if (!(entries[i] instanceof FileEntry) || !rule.matcher(entries[i].getName()).matches()) {
            continue;
        }
        Artifact artifact = factory.get(entries[i]);
        if (artifact != null) {
            result.add(artifact);
        }
    }
    return result;
}