Example usage for java.util TimeZone setDefault

List of usage examples for java.util TimeZone setDefault

Introduction

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

Prototype

public static void setDefault(TimeZone zone) 

Source Link

Document

Sets the TimeZone that is returned by the getDefault method.

Usage

From source file:org.transitime.applications.ScheduleGenerator.java

/**
 * Processes all command line options using Apache CLI.
 * Further info at http://commons.apache.org/proper/commons-cli/usage.html .
 * Returns the CommandLine object that provides access to each arg.
 * Exits if there is a parsing problem./*from   www. jav a2 s .  c  om*/
 * 
 * @param args The arguments from the command line
 * @return CommandLine object that provides access to all the args
 * @throws ParseException
 */
@SuppressWarnings("static-access") // Needed for using OptionBuilder
private static CommandLine processCommandLineOptions(String[] args) {
    // Specify the options
    Options options = new Options();

    options.addOption("h", false, "Display usage and help info.");

    options.addOption(OptionBuilder.hasArg().withArgName("dirName").isRequired()
            .withDescription("Directory where unzipped GTFS file are. Can "
                    + "be used if already have current version of GTFS data " + "and it is already unzipped.")
            .create("gtfsDirectoryName"));

    options.addOption(
            OptionBuilder.hasArg().withArgName("MM-dd-yyyy").isRequired()
                    .withDescription("Begin date for reading arrival/departure "
                            + "times from database. Format is MM-dd-yyyy, " + "such as 9-20-2014.")
                    .create("b"));

    options.addOption(OptionBuilder.hasArg().withArgName("MM-dd-yyyy")
            .withDescription("Optional end date for reading arrival/departure "
                    + "times from database. Format is MM-dd-yyyy, "
                    + "such as 9-20-2014. Will read up to current " + "time if this option is not set.")
            .create("e"));

    options.addOption(OptionBuilder.hasArg().withArgName("fraction").isRequired()
            .withDescription("Specifies fraction of times that should. " + "Good value is probably 0.2")
            .create("f"));

    options.addOption(
            OptionBuilder.hasArg().withArgName("secs")
                    .withDescription("How many seconds arrival/departure must be "
                            + "within mean for the trip/stop to not be filtered out.")
                    .create("allowableFromMean"));

    options.addOption(OptionBuilder.hasArg().withArgName("secs")
            .withDescription("How many seconds arrival/departure must be "
                    + "within original schedule time for the trip/stop to " + "not be filtered out.")
            .create("allowableFromOriginal"));

    options.addOption(OptionBuilder.hasArg().withArgName("minutes")
            .withDescription("For providing schedule adherence information. "
                    + "Specifies how many minutes a vehicle can be ahead of "
                    + "the schedule and still be considered on time. Default " + "is 1 minute.")
            .create("allowableEarly"));

    options.addOption(OptionBuilder.hasArg().withArgName("minutes")
            .withDescription("For providing schedule adherence information. "
                    + "Specifies how many minutes a vehicle can be behind "
                    + "schedule and still be considered on time. Default is " + "5 minutes.")
            .create("allowableLate"));

    options.addOption("updateFirstStopOfTrip", false,
            "Set if should modify time even for first stops of trips.");

    // Parse the options
    CommandLineParser parser = new BasicParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        // There was a parse problem so log the problem,
        // display the command line options so user knows
        // what is needed, and exit since can't continue.
        logger.error(e.getMessage());
        displayCommandLineOptions(options);
        System.exit(0);
    }

    // Handle help option
    if (cmd.hasOption("h")) {
        displayCommandLineOptions(options);
        System.exit(0);
    }

    // Get project ID from VM param transitime.core.agencyId
    agencyId = AgencyConfig.getAgencyId();
    if (agencyId == null) {
        displayCommandLineOptions(options);
        System.exit(0);
    }

    // Determine if should update even the first stops of trips.
    // Default is to no update the times for those stops.
    doNotUpdateFirstStopOfTrip = !cmd.hasOption("updateFirstStopOfTrip");

    // Set variables based on the command line args
    gtfsDirectoryName = cmd.getOptionValue("gtfsDirectoryName");

    // Time zones are complicated. Need to create both timeForUsingCalendar
    // and also set the system timezone so that times are processed 
    // correctly when read from the database. NOTE: must set default
    // timezone before calling anything from Time.java so that when the
    // SimpleDateFormat objects are created when the Time class is
    // initialized they will get the correct timezone.
    String timeZoneStr = GtfsAgencyReader.readTimezoneString(gtfsDirectoryName);
    TimeZone.setDefault(TimeZone.getTimeZone(timeZoneStr));
    timeForUsingCalendar = new Time(timeZoneStr);

    // Get the fraction early "e" command line option
    String fractionEarlyStr = cmd.getOptionValue("f");
    try {
        desiredFractionEarly = Double.parseDouble(fractionEarlyStr);
    } catch (NumberFormatException e1) {
        System.err.println("Paramater -f \"" + desiredFractionEarly + "\" could not be parsed.");
        System.exit(-1);
    }
    if (desiredFractionEarly < 0.0 || desiredFractionEarly > 0.5) {
        System.err.println("Paramater -f \"" + desiredFractionEarly + "\" must be between 0.0 and 0.5");
        System.exit(-1);

    }

    // Get the beginTime "b" command line option
    String beginDateStr = cmd.getOptionValue("b");
    try {
        beginTime = Time.parseDate(beginDateStr);

        // If specified time is in the future then reject
        if (beginTime.getTime() > System.currentTimeMillis()) {
            System.err.println("Paramater -b \"" + beginDateStr + "\" is in the future and therefore invalid!");
            System.exit(-1);
        }
    } catch (java.text.ParseException e) {
        System.err.println(
                "Paramater -b \"" + beginDateStr + "\" could not be parsed. Format must be \"MM-dd-yyyy\"");
        System.exit(-1);
    }

    // Get the optional endTime "e" command line option
    if (cmd.hasOption("e")) {
        String endDateStr = cmd.getOptionValue("e");
        try {
            // Get the end date specified and add 24 hours since want to 
            // load data up to the end of the date
            endTime = new Date(Time.parseDate(endDateStr).getTime() + 24 * Time.MS_PER_HOUR);

        } catch (java.text.ParseException e) {
            System.err.println(
                    "Paramater -e \"" + endDateStr + "\" could not be parsed. Format must be \"MM-dd-yyyy\"");
            System.exit(-1);
        }
    } else {
        // End time not specified so simply uses current time
        endTime = new Date();
    }

    // Get the optional "allowableFromMean" command line option.
    // Default is 15 minutes.
    allowableDifferenceFromMeanSecs = 15 * Time.SEC_PER_MIN;
    if (cmd.hasOption("allowableFromMean")) {
        String param = cmd.getOptionValue("allowableFromMean");
        try {
            allowableDifferenceFromMeanSecs = Integer.parseInt(param);
        } catch (NumberFormatException e) {
            System.err.println(
                    "Option -allowableFromMean value \"" + param + "\" could not be parsed into an integer.");
            System.exit(-1);
        }
    }

    // Get the optional "allowableFromOriginal" command line option
    // Default is 30 minutes.
    allowableDifferenceFromOriginalTimeSecs = 30 * Time.SEC_PER_MIN;
    if (cmd.hasOption("allowableFromOriginal")) {
        String param = cmd.getOptionValue("allowableFromOriginal");
        try {
            allowableDifferenceFromOriginalTimeSecs = Integer.parseInt(param);
        } catch (NumberFormatException e) {
            System.err.println("Option -allowableFromOriginal value \"" + param
                    + "\" could not be parsed into an integer.");
            System.exit(-1);
        }
    }

    // Get the optional "allowableEarly" and "allowableLate" command
    // line options. Default is 1 minute early and 5 minutes late.
    allowableEarlySecs = 1 * Time.SEC_PER_MIN;
    if (cmd.hasOption("allowableEarly")) {
        String param = cmd.getOptionValue("allowableEarly");
        try {
            allowableEarlySecs = (int) (Double.parseDouble(param) * Time.SEC_PER_MIN);
        } catch (NumberFormatException e) {
            System.err.println("Option -allowableEarly value \"" + param + "\" could not be parsed.");
            System.exit(-1);
        }
    }
    allowableLateSecs = 5 * Time.SEC_PER_MIN;
    if (cmd.hasOption("allowableLate")) {
        String param = cmd.getOptionValue("allowableLate");
        try {
            allowableLateSecs = (int) (Double.parseDouble(param) * Time.SEC_PER_MIN);
        } catch (NumberFormatException e) {
            System.err.println("Option -allowableLate value \"" + param + "\" could not be parsed.");
            System.exit(-1);
        }
    }

    // Return the CommandLine so that arguments can be further accessed
    return cmd;
}

From source file:org.jfree.data.time.junit.MillisecondTest.java

/**
 * Some checks for the getFirstMillisecond() method.
 *//*w w w . j a v  a2s  .  c  o  m*/
public void testGetFirstMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Millisecond m = new Millisecond(500, 15, 43, 15, 1, 4, 2006);
    assertEquals(1143902595500L, m.getFirstMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}

From source file:org.jfree.data.time.MonthTest.java

/**
 * Some checks for the getFirstMillisecond() method.
 *//*  w  ww  . j  av a 2 s .  c  o m*/
@Test
public void testGetFirstMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Month m = new Month(3, 1970);
    assertEquals(5094000000L, m.getFirstMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}

From source file:org.jfree.data.time.junit.HourTest.java

/**
     * Some checks for the getFirstMillisecond() method.
     *//*  ww  w.ja  v  a2  s .c o m*/
public void testGetFirstMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Hour h = new Hour(15, 1, 4, 2006);
    assertEquals(1143900000000L, h.getFirstMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}

From source file:org.jfree.data.time.DayTest.java

/**
 * Some checks for the getFirstMillisecond() method.
 *//*  w  w w  .j a  v a 2 s  . co m*/
@Test
public void testGetFirstMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Day d = new Day(1, 3, 1970);
    assertEquals(5094000000L, d.getFirstMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}

From source file:org.agiso.tempel.Tempel.java

/**
 * //  w w w . jav  a  2s . com
 * 
 * @param properties
 * @throws Exception 
 */
private Map<String, Object> addRuntimeProperties(Map<String, Object> properties) throws Exception {
    Map<String, Object> props = new HashMap<String, Object>();

    // Okrelanie lokalizacji daty/czasu uywanej do wypenienia paramtrw szablonw
    // zawierajcych dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL:
    Locale date_locale;
    if (properties.containsKey(UP_DATE_LOCALE)) {
        date_locale = LocaleUtils.toLocale((String) properties.get(UP_DATE_LOCALE));
        Locale.setDefault(date_locale);
    } else {
        date_locale = Locale.getDefault();
    }

    TimeZone time_zone;
    if (properties.containsKey(UP_TIME_ZONE)) {
        time_zone = TimeZone.getTimeZone((String) properties.get(UP_DATE_LOCALE));
        TimeZone.setDefault(time_zone);
    } else {
        time_zone = TimeZone.getDefault();
    }

    // Wyznaczanie daty, na podstawie ktrej zostan wypenione parametry szablonw
    // przechowujce dat/czas w formatach DateFormat.SHORT, .MEDIUM, .LONG i .FULL.
    // Odbywa si w oparciu o wartoci parametrw 'date_format' i 'date'. Parametr
    // 'date_format' definiuje format uywany do parsowania acucha reprezentujcego
    // dat okrelon parametrem 'date'. Parametr 'date_format' moe nie by okrelony.
    // W takiej sytuacji uyty jest format DateFormat.LONG aktywnej lokalizacji (tj.
    // systemowej, ktra moe by przedefiniowana przez parametr 'date_locale'), ktry
    // moe by przedefiniowany przez parametry 'date_format_long' i 'time_format_long':
    Calendar calendar = Calendar.getInstance(date_locale);
    if (properties.containsKey(RP_DATE)) {
        String date_string = (String) properties.get(RP_DATE);
        if (properties.containsKey(RP_DATE_FORMAT)) {
            String date_format = (String) properties.get(RP_DATE_FORMAT);
            DateFormat formatter = new SimpleDateFormat(date_format);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        } else if (properties.containsKey(UP_DATE_FORMAT_LONG) && properties.containsKey(UP_TIME_FORMAT_LONG)) {
            // TODO: Zaoenie, e format data-czas jest zoony z acucha daty i czasu rozdzelonych spacj:
            // 'UP_DATE_FORMAT_LONG UP_TIME_FORMAT_LONG'
            DateFormat formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG) + " "
                    + (String) properties.get(UP_TIME_FORMAT_LONG), date_locale);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        } else {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG,
                    date_locale);
            formatter.setTimeZone(time_zone);
            calendar.setTime(formatter.parse(date_string));
        }
    }

    // Jeli nie okrelono, wypenianie parametrw przechowujcych poszczeglne
    // skadniki daty, tj. rok, miesic i dzie:
    if (!properties.containsKey(TP_YEAR)) {
        props.put(TP_YEAR, calendar.get(Calendar.YEAR));
    }
    if (!properties.containsKey(TP_MONTH)) {
        props.put(TP_MONTH, calendar.get(Calendar.MONTH));
    }
    if (!properties.containsKey(TP_DAY)) {
        props.put(TP_DAY, calendar.get(Calendar.DAY_OF_MONTH));
    }

    // Jeli nie okrelono, wypenianie parametrw przechowujcych dat i czas w
    // formatach SHORT, MEDIUM, LONG i FULL (na podstawie wyznaczonej lokalizacji):
    Date date = calendar.getTime();
    if (!properties.containsKey(TP_DATE_SHORT)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_SHORT)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_SHORT), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.SHORT, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_SHORT, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_MEDIUM)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_MEDIUM)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_MEDIUM), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.MEDIUM, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_MEDIUM, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_LONG)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_LONG)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_LONG), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.LONG, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_LONG, formatter.format(date));
    }
    if (!properties.containsKey(TP_DATE_FULL)) {
        DateFormat formatter;
        if (properties.containsKey(UP_DATE_FORMAT_FULL)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_DATE_FORMAT_FULL), date_locale);
        } else {
            formatter = DateFormat.getDateInstance(DateFormat.FULL, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_DATE_FULL, formatter.format(date));
    }

    if (!properties.containsKey(TP_TIME_SHORT)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_SHORT)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_SHORT), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.SHORT, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_SHORT, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_MEDIUM)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_MEDIUM)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_MEDIUM), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.MEDIUM, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_MEDIUM, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_LONG)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_LONG)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_LONG), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.LONG, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_LONG, formatter.format(date));
    }
    if (!properties.containsKey(TP_TIME_FULL)) {
        DateFormat formatter;
        if (properties.containsKey(UP_TIME_FORMAT_FULL)) {
            formatter = new SimpleDateFormat((String) properties.get(UP_TIME_FORMAT_FULL), date_locale);
        } else {
            formatter = DateFormat.getTimeInstance(DateFormat.FULL, date_locale);
        }
        formatter.setTimeZone(time_zone);
        props.put(TP_TIME_FULL, formatter.format(date));
    }

    return props;
}

From source file:org.jfree.data.time.QuarterTest.java

/**
 * Some checks for the getFirstMillisecond() method.
 *///from ww w  . ja  v a 2s. co  m
@Test
public void testGetFirstMillisecond() {
    Locale saved = Locale.getDefault();
    Locale.setDefault(Locale.UK);
    TimeZone savedZone = TimeZone.getDefault();
    TimeZone.setDefault(TimeZone.getTimeZone("Europe/London"));
    Quarter q = new Quarter(3, 1970);
    assertEquals(15634800000L, q.getFirstMillisecond());
    Locale.setDefault(saved);
    TimeZone.setDefault(savedZone);
}

From source file:org.sipfoundry.sipxconfig.admin.time.TimeManagerImpl.java

public void setSystemTimezone(String timezone) {
    String errorMsg = "Error when changing time zone";
    ProcessBuilder pb = new ProcessBuilder(getLibExecDirectory() + File.separator + TIMEZONE_BINARY);
    pb.command().add(timezone);/*from  ww w.  j  a  v a  2s . c om*/
    try {
        LOG.debug(pb.command());
        Process process = pb.start();
        BufferedReader scriptErrorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        String errorLine = scriptErrorReader.readLine();
        while (errorLine != null) {
            LOG.warn("sipx-sudo-timezone: " + errorLine);
            errorLine = scriptErrorReader.readLine();
        }
        int code = process.waitFor();
        if (code != 0) {
            errorMsg = String.format("Error when changing time zone. Exit code: %d", code);
            LOG.error(errorMsg);
        }
        TimeZone tz = TimeZone.getTimeZone(timezone);
        TimeZone.setDefault(tz);
    } catch (IOException e) {
        LOG.error(errorMsg, e);
    } catch (InterruptedException e) {
        LOG.error(errorMsg, e);
    }
}

From source file:tw.idv.gasolin.pycontw2012.ui.ScheduleFragment.java

private void setupDay(LayoutInflater inflater, long startMillis) {
    Day day = new Day();

    // Setup data
    day.index = mDays.size();//from   ww  w.ja va 2s  . co m
    day.timeStart = startMillis;
    day.timeEnd = startMillis + DateUtils.DAY_IN_MILLIS;
    day.blocksUri = CoscupContract.Blocks.buildBlocksBetweenDirUri(day.timeStart, day.timeEnd);

    // Setup views
    day.rootView = (ViewGroup) inflater.inflate(R.layout.blocks_content, null);

    day.scrollView = (ObservableScrollView) day.rootView.findViewById(R.id.blocks_scroll);
    day.scrollView.setOnScrollListener(this);

    day.blocksView = (BlocksLayout) day.rootView.findViewById(R.id.blocks);
    day.nowView = day.rootView.findViewById(R.id.blocks_now);

    day.blocksView.setDrawingCacheEnabled(true);
    day.blocksView.setAlwaysDrawnWithCacheEnabled(true);

    TimeZone.setDefault(UIUtils.CONFERENCE_TIME_ZONE);
    day.label = DateUtils.formatDateTime(getActivity(), startMillis, TIME_FLAGS);

    mWorkspace.addView(day.rootView);
    mDays.add(day);
}

From source file:com.google.android.apps.iosched.ui.ScheduleFragment.java

private void setupDay(LayoutInflater inflater, long startMillis) {
    Day day = new Day();

    // Setup data
    day.index = mDays.size();//from   w  w w .  j a v a2 s.c  om
    day.timeStart = startMillis;
    day.timeEnd = startMillis + DateUtils.DAY_IN_MILLIS;
    day.blocksUri = ScheduleContract.Blocks.buildBlocksBetweenDirUri(day.timeStart, day.timeEnd);

    // Setup views
    day.rootView = (ViewGroup) inflater.inflate(R.layout.blocks_content, null);

    day.scrollView = (ObservableScrollView) day.rootView.findViewById(R.id.blocks_scroll);
    day.scrollView.setOnScrollListener(this);

    day.blocksView = (BlocksLayout) day.rootView.findViewById(R.id.blocks);
    day.nowView = day.rootView.findViewById(R.id.blocks_now);

    day.blocksView.setDrawingCacheEnabled(true);
    day.blocksView.setAlwaysDrawnWithCacheEnabled(true);

    TimeZone.setDefault(UIUtils.CONFERENCE_TIME_ZONE);
    day.label = DateUtils.formatDateTime(getActivity(), startMillis, TIME_FLAGS);

    mWorkspace.addView(day.rootView);
    mDays.add(day);
}