Example usage for java.util TimeZone getTimeZone

List of usage examples for java.util TimeZone getTimeZone

Introduction

In this page you can find the example usage for java.util TimeZone getTimeZone.

Prototype

public static TimeZone getTimeZone(ZoneId zoneId) 

Source Link

Document

Gets the TimeZone for the given zoneId .

Usage

From source file:mk.finki.ranggo.aggregator.Aggregator.java

private static void update(String date, ContentsAggregator aggregator) {
    //if 'date' is null, the method aggregates contents published on the current date
    //if it is, it aggregates the data published on that date
    //parameter format is dd.mm.yyyy, assumed UTC+0

    //parse or generate date object 
    Date dateObj = null;/* w ww.  j  ava  2 s.c  o  m*/
    if (date != null) {
        try {
            final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            dateObj = simpleDateFormat.parse(date);

        } catch (ParseException e) {
        }
    } else {
        //no date parameter, default case is today
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
        dateObj = calendar.getTime();
    }

    if (dateObj != null) {

        try {
            aggregator.aggregateGoogleNewsRSSFeed(dateObj);
        } catch (ContentsAggregatorException exception) {
            //log this
        }

        try {
            aggregator.aggregateHuffingtonPost();
        } catch (ContentsAggregatorException exception) {
            //log this
        }

        try {
            aggregator.aggregateDnevnik();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateKurir();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateLibertas();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateNovaTV();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateRepublika();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateTelma();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateUtrinskiVesnik();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateVecher();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateVest();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateVesti24();
        } catch (ContentsAggregatorException exception) {

        }

        try {
            aggregator.aggregateNYTimes(dateObj);
        } catch (ContentsAggregatorException exception) {

        }
        try {
            aggregator.aggregateTheGuardian(dateObj);
        } catch (ContentsAggregatorException exception) {

        }
    }
}

From source file:Main.java

/**
 * Parses an xs:dateTime attribute value, returning the parsed timestamp in milliseconds since
 * the epoch./*from  w  ww. jav  a2 s. com*/
 *
 * @param value The attribute value to parse.
 * @return The parsed timestamp in milliseconds since the epoch.
 */
public static long parseXsDateTime(String value) throws ParseException {
    Matcher matcher = XS_DATE_TIME_PATTERN.matcher(value);
    if (!matcher.matches()) {
        throw new ParseException("Invalid date/time format: " + value, 0);
    }

    int timezoneShift;
    if (matcher.group(9) == null) {
        // No time zone specified.
        timezoneShift = 0;
    } else if (matcher.group(9).equalsIgnoreCase("Z")) {
        timezoneShift = 0;
    } else {
        timezoneShift = ((Integer.parseInt(matcher.group(12)) * 60 + Integer.parseInt(matcher.group(13))));
        if (matcher.group(11).equals("-")) {
            timezoneShift *= -1;
        }
    }

    Calendar dateTime = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

    dateTime.clear();
    // Note: The month value is 0-based, hence the -1 on group(2)
    dateTime.set(Integer.parseInt(matcher.group(1)), Integer.parseInt(matcher.group(2)) - 1,
            Integer.parseInt(matcher.group(3)), Integer.parseInt(matcher.group(4)),
            Integer.parseInt(matcher.group(5)), Integer.parseInt(matcher.group(6)));
    if (!TextUtils.isEmpty(matcher.group(8))) {
        final BigDecimal bd = new BigDecimal("0." + matcher.group(8));
        // we care only for milliseconds, so movePointRight(3)
        dateTime.set(Calendar.MILLISECOND, bd.movePointRight(3).intValue());
    }

    long time = dateTime.getTimeInMillis();
    if (timezoneShift != 0) {
        time -= timezoneShift * 60000;
    }

    return time;
}

From source file:Main.java

/**
 * Expects an XML xs:dateTime lexical format string, as in
 * <code>2005-10-24T11:57:31.000+01:00</code>. Some bad MXML files miss
 * timezone or milliseconds information, thus a certain amount of tolerance
 * is applied towards malformed timestamp string representations. If
 * unparseable, this method will return <code>null</code>.
 * /*from w  ww.  j  a  v a  2  s  .  co  m*/
 * @param xmlLexicalString
 * @return
 */
public static Date parseXsDateTime(String xsDateTime) {
    // match pattern against timestamp string
    Matcher matcher = xsDtPattern.matcher(xsDateTime);
    if (matcher.matches() == true) {
        // extract data particles from matched groups / subsequences
        int year = Integer.parseInt(matcher.group(1));
        int month = Integer.parseInt(matcher.group(2)) - 1;
        int day = Integer.parseInt(matcher.group(3));
        int hour = Integer.parseInt(matcher.group(4));
        int minute = Integer.parseInt(matcher.group(5));
        int second = Integer.parseInt(matcher.group(6));
        int millis = 0;
        // probe for successful parsing of milliseconds
        if (matcher.group(7) != null) {
            millis = Integer.parseInt(matcher.group(8));
        }
        cal.set(year, month, day, hour, minute, second);
        cal.set(GregorianCalendar.MILLISECOND, millis);
        String tzString = matcher.group(9);
        if (tzString != null) {
            // timezone matched
            tzString = "GMT" + tzString.replace(":", "");
            cal.setTimeZone(TimeZone.getTimeZone(tzString));
        } else {
            cal.setTimeZone(TimeZone.getTimeZone("GMT"));
        }
        return cal.getTime();
    } else {
        return null;
    }
}

From source file:Main.java

public Main() {
    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();/*w w w .  j  av  a  2s .  c  om*/
    model.setValue(date);
    spinner = new JSpinner(model);
    spinner.addChangeListener(e -> {
        Date d = (Date) ((JSpinner) e.getSource()).getValue();
        for (int i = 0; i < labels.length; i++) {
            labels[i].setText(formats[i].format(d));
        }
    });
    format = ((JSpinner.DateEditor) spinner.getEditor()).getFormat();
    format.setTimeZone(TimeZone.getTimeZone(zones[0]));
    format.applyPattern("yyyy-MM-dd HH:mm:ss");
    format.applyPattern("HH:mm:ss");
    panel = new JPanel(new GridLayout(zones.length, 2, 10, 10));
    for (int i = 0; i < zones.length; i++) {
        formats[i] = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
        formats[i] = new SimpleDateFormat("HH:mm:ss");
        formats[i].setTimeZone(TimeZone.getTimeZone(zones[i]));
        JLabel label = new JLabel(zones[i]);
        labels[i] = new JLabel(formats[i].format(date));
        labels[i].setHorizontalAlignment(JLabel.RIGHT);
        panel.add(label);
        panel.add(labels[i]);
    }
    frame.setLayout(new BorderLayout(10, 10));
    frame.add(spinner, BorderLayout.NORTH);
    frame.add(panel, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

From source file:edu.kit.dama.mdm.audit.impl.ConsoleConsumer.java

@Override
public void consume(AuditEvent entry) {
    StringBuilder b = new StringBuilder();
    final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    b.append(entry.getPid()).append("|").append(entry.getEventType()).append("|").append(entry.getCategory())
            .append("|").append(df.format(entry.getEventDate())).append("|").append(entry.getOwner())
            .append("|").append(entry.getAgent()).append("|").append(entry.getResource()).append("|")
            .append(entry.getDetails());
    System.out.println(b.toString());
}

From source file:Main.java

/**
 * Parse a date from ISO-8601 formatted string. It expects a format yyyy-MM-ddThh:mm:ss[.sss][Z|[+-]hh:mm]
 *
 * @param date ISO string to parse in the appropriate format.
 * @return the parsed date//from   www  .  j  av a  2s .  c  o  m
 * @throws IllegalArgumentException if the date is not in the appropriate format
 */
public static Date parse(String date) {
    try {
        int offset = 0;

        // extract year
        int year = parseInt(date, offset, offset += 4);
        checkOffset(date, offset, '-');

        // extract month
        int month = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, '-');

        // extract day
        int day = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, 'T');

        // extract hours, minutes, seconds and milliseconds
        int hour = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, ':');

        int minutes = parseInt(date, offset += 1, offset += 2);
        checkOffset(date, offset, ':');

        int seconds = parseInt(date, offset += 1, offset += 2);
        // milliseconds can be optional in the format
        int milliseconds = 0; // always use 0 otherwise returned date will include millis of current time
        if (date.charAt(offset) == '.') {
            checkOffset(date, offset, '.');
            milliseconds = parseInt(date, offset += 1, offset += 3);
        }

        // extract timezone
        String timezoneId;
        char timezoneIndicator = date.charAt(offset);
        if (timezoneIndicator == '+' || timezoneIndicator == '-') {
            timezoneId = GMT_ID + date.substring(offset);
        } else if (timezoneIndicator == 'Z') {
            timezoneId = GMT_ID;
        } else {
            throw new IndexOutOfBoundsException("Invalid time zone indicator " + timezoneIndicator);
        }
        TimeZone timezone = TimeZone.getTimeZone(timezoneId);
        if (!timezone.getID().equals(timezoneId)) {
            throw new IndexOutOfBoundsException();
        }

        Calendar calendar = new GregorianCalendar(timezone);
        calendar.setLenient(false);
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, day);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);
        calendar.set(Calendar.MILLISECOND, milliseconds);

        return calendar.getTime();
    } catch (IndexOutOfBoundsException e) {
        throw new IllegalArgumentException("Failed to parse date " + date, e);
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("Failed to parse date " + date, e);
    } catch (IllegalArgumentException e) {
        throw new IllegalArgumentException("Failed to parse date " + date, e);
    }
}

From source file:com.kylinolap.dict.DateStrDictionary.java

static SimpleDateFormat getDateFormat(String datePattern) {
    ThreadLocal<SimpleDateFormat> formatThreadLocal = threadLocalMap.get(datePattern);
    if (formatThreadLocal == null) {
        threadLocalMap.put(datePattern, formatThreadLocal = new ThreadLocal<SimpleDateFormat>());
    }/*w  w w  .  jav  a 2  s .  co  m*/
    SimpleDateFormat format = formatThreadLocal.get();
    if (format == null) {
        format = new SimpleDateFormat(datePattern);
        format.setTimeZone(TimeZone.getTimeZone("GMT")); // NOTE: this must
                                                         // be GMT to
                                                         // calculate
                                                         // epoch date
                                                         // correctly
        formatThreadLocal.set(format);
    }
    return format;
}

From source file:com.collabnet.ccf.core.utils.DateUtil.java

public static Date convertDateToTimeZone(Date date, String toTimeZone) {
    Calendar toCal = new GregorianCalendar(TimeZone.getTimeZone(toTimeZone));
    Calendar fromCal = new GregorianCalendar();
    fromCal.setTime(date);/*  ww  w .  j  a  va  2  s .c  o m*/

    toCal.set(fromCal.get(Calendar.YEAR), fromCal.get(Calendar.MONTH), fromCal.get(Calendar.DAY_OF_MONTH),
            fromCal.get(Calendar.HOUR_OF_DAY), fromCal.get(Calendar.MINUTE), fromCal.get(Calendar.SECOND));
    toCal.set(Calendar.MILLISECOND, fromCal.get(Calendar.MILLISECOND));

    return toCal.getTime();
}

From source file:ru.retbansk.utils.marshaller.Jaxb2MarshallerTest.java

@BeforeClass
public static void beforeClass() {
    TaskReport taskReport = new TaskReport();
    Date date = new Date();
    Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    calendar.clear();/*from www  .  j  av  a 2 s. c  o m*/
    calendar.set(Calendar.DATE, 1);
    calendar.set(Calendar.MONTH, Calendar.JANUARY);
    calendar.set(Calendar.YEAR, 1981);
    date = calendar.getTime();
    taskReport.setDate(date);
    taskReport.setElapsedTime(4);
    taskReport.setStatus(STATUS);
    taskReport.setWorkDescription(WORK_DESCRIPTION);
    list = new ArrayList<TaskReport>();
    list.add(taskReport);

}

From source file:com.bourke.kitchentimer.utils.Utils.java

/**
 * /*from www  . j  ava  2 s  .c  o  m*/
 * @param totalSeconds
 * @param timer
 * @return
 */
public static String formatTime(long totalSeconds, int timer) {
    if (timer == 0) {
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
        return sdf.format(new Date(totalSeconds * 1000));
    } else {

        String seconds = Integer.toString((int) (totalSeconds % 60));
        String minutes = Integer.toString((int) (totalSeconds / 60));
        if (seconds.length() < 2) {
            seconds = "0" + seconds;
        }
        if (minutes.length() < 2) {
            minutes = "0" + minutes;
        }
        return minutes + ":" + seconds;
    }
}