Example usage for java.text SimpleDateFormat setTimeZone

List of usage examples for java.text SimpleDateFormat setTimeZone

Introduction

In this page you can find the example usage for java.text SimpleDateFormat setTimeZone.

Prototype

public void setTimeZone(TimeZone zone) 

Source Link

Document

Sets the time zone for the calendar of this DateFormat object.

Usage

From source file:com.krawler.common.util.BaseStringUtil.java

private static Date getUserTimeZoneDate(String userTimezone) { // use for unit testing of time zone related to creation date of modules
                                                               // records
    Date date = new Date();
    System.out.println(date);/*from  w ww  . j av a2s  .c  o m*/
    SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
    // SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
    sdf.setTimeZone(TimeZone.getTimeZone(userTimezone)); // replace timezine
                                                         // with user
                                                         // timezone
    String datestr = sdf.format(date);
    System.out.println(datestr);
    String[] datearr = datestr.split(" ");

    // datearr[4] contains user time zone format which is replaced by space.
    // so that new date function use system time zone format which is
    // already set at user session creation time
    String newstr = datestr.replace(datearr[4], " ");

    Date newdate = new Date(newstr);
    System.out.println(newdate);
    return newdate;
}

From source file:home.vitaly.simulator.RunSimulator.java

private String getTimeStamp(Long seconds) {
    Date date = new Date(seconds * 1000);
    SimpleDateFormat sdf = new SimpleDateFormat("HHmmss", Locale.ENGLISH);
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    //   String formattedDate = sdf.format(date);
    //   System.out.println(formattedDate); 
    return sdf.format(date);
}

From source file:com.github.lynxdb.server.api.http.mappers.QueryRequest.java

/**
 * /*from   w w  w.  j  a va2 s. c o m*/
 * Only supporting UTC timezone rightnow
 * 
 * @param _time (String|Integer|Long) the time to Object to parse
 * @return the time in s
 * @throws InvalidTimeException 
 */
public static long parseTime(Object _time) throws InvalidTimeException {
    if (_time instanceof Integer || _time instanceof Long) {
        if ((long) _time > Integer.MAX_VALUE) {
            return Math.floorDiv((long) _time, 1000);
        }
        return (long) _time;
    } else if (_time instanceof String) {
        String time = _time.toString();
        if (time.endsWith("-ago")) {
            long amount = parseDuration(time.substring(0, time.length() - 4));
            if (amount >= 1000) {
                return Math.floorDiv((System.currentTimeMillis() - amount), 1000);
            } else {
                throw new InvalidTimeException(
                        "Invalid time : " + _time + ". Must be greater than or equal to 1s");
            }
        } else {
            SimpleDateFormat fmt;
            switch (time.length()) {
            case 10:
                fmt = new SimpleDateFormat("yyyy/MM/dd");
                break;
            case 16:
                if (time.contains("-")) {
                    fmt = new SimpleDateFormat("yyyy/MM/dd-HH:mm");
                } else {
                    fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm");
                }
                break;
            case 19:
                if (time.contains("-")) {
                    fmt = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss");
                } else {
                    fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                }
                break;
            default:
                throw new InvalidTimeException("Invalid time date : " + _time);
            }
            fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
            try {
                return Math.floorDiv(fmt.parse(time).getTime(), 1000);
            } catch (ParseException ex) {
                throw new InvalidTimeException("Invalid time date : " + _time);
            }
        }
    } else {
        throw new InvalidTimeException("Unsupported time type : " + _time);
    }
}

From source file:com.funambol.exchange.util.DateTools.java

/**
 * Converts a all day Funambol date to an allday ExchangeDate
 * // w  ww . j a  va2 s  .  c om
 * @param date
 * @param timezone
 * @param isAStartDate
 * @return
 * @throws com.funambol.exchange.xml.XmlParseException
 */
public static String convertDayToWebDavDate(String date, String timezone) throws XmlParseException {
    SimpleDateFormat formatter;
    Date dt;
    String wedDavDate, value;
    String timePart = null;

    if (date != null && date.length() > 0) {
        if (date.length() != 8) {
            date = date.replaceAll("-", "");
        }
        timePart = "T000000Z";
        value = date + timePart;

        formatter = new SimpleDateFormat(DATE_FORMAT_PDI);

        try {
            formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
            dt = formatter.parse(value);
            long time = dt.getTime();
            long offset = TimeZone.getTimeZone(timezone).getOffset(time);
            dt = new Date(time - offset);
        } catch (ParseException e) {
            throw new XmlParseException("Error converting date", e);
        }
        formatter.applyPattern(DATE_FORMAT_WEBDAV);
        wedDavDate = formatter.format(dt);

    } else {
        wedDavDate = null;
    }

    return wedDavDate;
}

From source file:net.servicefixture.converter.CalendarConverter.java

public String toString(Object source) {
    SimpleDateFormat formatter = new SimpleDateFormat(DateConverter.DATE_FORMAT);
    formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
    return formatter.format(((Calendar) source).getTime());
}

From source file:jp.classmethod.aws.brian.util.BrianClientObjectMapper.java

/**
 * Instantiate./*from www.  j a  v a  2s.co m*/
 */
public BrianClientObjectMapper() {
    SimpleModule brianModule = new SimpleModule("brianClientModule", VERSION);
    registerModule(brianModule);
    registerModule(new Jdk8Module());

    configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    df.setTimeZone(TimeZone.getTimeZone("Universal"));
    setDateFormat(df);
}

From source file:org.springframework.social.bitbucket.api.impl.UTCDateDeserializer.java

@Override
public Date deserialize(JsonParser jp, DeserializationContext ctxt)
        throws IOException, JsonProcessingException {
    try {/*www  .j av a 2  s.  c om*/
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.ENGLISH);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        return dateFormat.parse(jp.getText());
    } catch (ParseException e) {
        throw new JsonParseException("Can't parse date : " + jp.getText(), jp.getCurrentLocation());
    }
}

From source file:Main.java

public void makeUI() {
    String[] zones = { "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Calcutta", "Europe/Paris", "Europe/London",
            "America/New_York", "America/Los_Angeles" };
    JLabel[] labels = new JLabel[zones.length];
    SimpleDateFormat[] formats = new SimpleDateFormat[zones.length];
    JFrame frame = new JFrame();

    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();// ww w . j  ava2s.  c om
    SpinnerDateModel model = new SpinnerDateModel();
    model.setValue(date);
    JSpinner spinner = new JSpinner(model);
    spinner.addChangeListener(new ChangeListener() {

        @Override
        public void stateChanged(ChangeEvent e) {
            Date date = (Date) ((JSpinner) e.getSource()).getValue();
            for (int i = 0; i < labels.length; i++) {
                labels[i].setText(formats[i].format(date));
            }
        }
    });
    SimpleDateFormat format = ((JSpinner.DateEditor) spinner.getEditor()).getFormat();
    format.setTimeZone(TimeZone.getTimeZone(zones[0]));
    format.applyPattern("yyyy-MM-dd HH:mm:ss");
    JPanel 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].setTimeZone(TimeZone.getTimeZone(zones[i]));
        JLabel label = new JLabel(zones[i]);
        labels[i] = new JLabel(formats[i].format(date));
        panel.add(label);
        panel.add(labels[i]);
    }
    frame.setLayout(new BorderLayout());
    frame.add(spinner, BorderLayout.NORTH);
    frame.add(panel, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
}

From source file:com.sonymobile.tools.gerrit.gerritevents.dto.events.EventCreatedOnTest.java

/**
 * Given an event in JSON format//  w  w  w .  ja  v  a2  s .c o m
 * When it is converted to an Event Object
 * Then the eventCreatedOn attribute can be parsed as a Date.
 * @throws IOException if we cannot load json from file.
 */
@Test
public void fromJsonShouldProvideValidDateFromEventCreatedOn() throws IOException {
    InputStream stream = getClass().getResourceAsStream("DeserializeEventCreatedOnTest.json");
    String json = IOUtils.toString(stream);
    JSONObject jsonObject = JSONObject.fromObject(json);
    GerritEvent evt = GerritJsonEventFactory.getEvent(jsonObject);
    GerritTriggeredEvent gEvt = (GerritTriggeredEvent) evt;
    Date dt = gEvt.getEventCreatedOn();
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(df.format(dt));
    String expectDateString = "2014-12-09 14:02:52";
    assertEquals(expectDateString, df.format(dt));
}

From source file:com.funambol.exchange.util.DateTools.java

/**
 * Make a webdav tag date from a date//from   w w w  . j  a v  a2 s  . co m
 * 
 * @param date
 *            date
 * @param timeZone
 * @return webdav tag date
 * @throws XmlParseException
 */
public static String dateToWebDavTag(String date, TimeZone timeZone) throws Exception {

    SimpleDateFormat formatter;
    String webDavDate;
    Date dt;

    if (date != null) {

        String format = DATETIME_FORMAT_CLIENT_UTC;
        if (date.indexOf("Z") == -1) {
            //
            // for nokia phone utc bug
            //
            format = DATETIME_FORMAT_CLIENT_NO_UTC;
        }
        formatter = new SimpleDateFormat(format);
        if (timeZone != null) {
            formatter.setTimeZone(timeZone);
        }
        dt = formatter.parse(date);

        webDavDate = dateToWebDavTag(dt);

    } else {
        webDavDate = "";
    }

    return webDavDate;
}