Java Code Examples for java.util.TimeZone#inDaylightTime()

The following examples show how to use java.util.TimeZone#inDaylightTime() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: OpenRate   File: ConversionUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This function converts a date to a GMT date
 *
 * @param date The date to convert
 * @return The date at GMT
 */
public Date getGmtDate( Date date )
{
   TimeZone tz = TimeZone.getDefault();
   Date ret = new Date( date.getTime() - tz.getRawOffset() );

   // if we are now in DST, back off by the delta.  Note that we are
   // checking the GMT date, this is the KEY.
   if ( tz.inDaylightTime( ret ))
   {
      Date dstDate = new Date( ret.getTime() - tz.getDSTSavings() );

      // check to make sure we have not crossed back into standard time
      // this happens when we are on the cusp of DST (7pm the day before
      // the change for PDT)
      if ( tz.inDaylightTime( dstDate ))
      {
         ret = dstDate;
      }
   }

   return ret;
}
 
Example 2
Source Project: jphp   File: DateFunctions.java    License: Apache License 2.0 6 votes vote down vote up
public static Memory gettimeofday(boolean getAsFloat) {
    long msec_time = System.currentTimeMillis();

    if (getAsFloat) {
        double now = msec_time / 1000.0;

        return new DoubleMemory(now);
    } else {
        ArrayMemory result = new ArrayMemory();

        TimeZone timeZone = TimeZone.getDefault();
        long sec = msec_time / 1000;
        long usec = (msec_time % 1000) * 1000;
        long minuteswest = -timeZone.getOffset(msec_time) / MSEC_IN_MIN;
        boolean is_dst = timeZone.inDaylightTime(new Date(msec_time));

        result.refOfIndex("sec").assign(sec);
        result.refOfIndex("usec").assign(usec);
        result.refOfIndex("minuteswest").assign(minuteswest);
        result.refOfIndex("dsttime").assign(is_dst ? 1 : 0);

        return result.toConstant();
    }
}
 
Example 3
/**
 * Returns the local time info as a byte array, useful for implementing {@link BleServices#currentTime()} for example.
 */
public static byte[] getLocalTimeInfo()
{
	final byte[] info = new byte[2];
	final TimeZone timeZone = TimeZone.getDefault();
	int offset = timeZone.getOffset( System.currentTimeMillis() );
	offset /= 1800000; // see CTS spec for why this is like this: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.time_zone.xml
	offset *= 2;
	info[0] = (byte)offset;
	final byte dst;

	if ( timeZone.useDaylightTime() && timeZone.inDaylightTime( new GregorianCalendar().getTime() ) )
	{
		final int savings = timeZone.getDSTSavings();
		dst = (byte)(savings / 900000);
	}
	else
	{
		dst = 0;
	}

	info[1] = dst;

	return info;
}
 
Example 4
Source Project: jpHolo   File: Globalization.java    License: MIT License 5 votes vote down vote up
private JSONObject getIsDayLightSavingsTime(JSONArray options) throws GlobalizationError{
    JSONObject obj = new JSONObject();
    boolean dst = false;
    try{
        Date date = new Date((Long)options.getJSONObject(0).get(DATE));
        //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone();
        TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone());
        dst = tz.inDaylightTime(date); //get daylight savings data from date object and user timezone settings

        return obj.put("dst",dst);
    }catch(Exception ge){
        throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
    }
}
 
Example 5
public void test_printText() {
    Random r = RandomFactory.getRandom();
    int N = 8;
    Locale[] locales = Locale.getAvailableLocales();
    Set<String> zids = ZoneRulesProvider.getAvailableZoneIds();
    ZonedDateTime zdt = ZonedDateTime.now();

    //System.out.printf("locale==%d, timezone=%d%n", locales.length, zids.size());
    while (N-- > 0) {
        zdt = zdt.withDayOfYear(r.nextInt(365) + 1)
                 .with(ChronoField.SECOND_OF_DAY, r.nextInt(86400));
        for (String zid : zids) {
            if (zid.equals("ROC") || zid.startsWith("Etc/GMT")) {
                continue;      // TBD: match jdk behavior?
            }
            zdt = zdt.withZoneSameLocal(ZoneId.of(zid));
            TimeZone tz = TimeZone.getTimeZone(zid);
            boolean isDST = tz.inDaylightTime(new Date(zdt.toInstant().toEpochMilli()));
            for (Locale locale : locales) {
                printText(locale, zdt, TextStyle.FULL, tz,
                        tz.getDisplayName(isDST, TimeZone.LONG, locale));
                printText(locale, zdt, TextStyle.SHORT, tz,
                        tz.getDisplayName(isDST, TimeZone.SHORT, locale));
            }
        }
    }
}
 
Example 6
Source Project: xDrip-plus   File: Utils.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static Date receiverTimeToDate(long delta) {
    int currentTZOffset = TimeZone.getDefault().getRawOffset();
    long epochMS = 1230768000000L;  // Jan 01, 2009 00:00 in UTC
    long milliseconds = epochMS - currentTZOffset;
    long timeAdd = milliseconds + (1000L * delta);
    TimeZone tz = TimeZone.getDefault();
    if (tz.inDaylightTime(new Date())) timeAdd = timeAdd - (1000 * 60 * 60);
    return new Date(timeAdd);
}
 
Example 7
public static Date convertToUtcDate(Date localDate) {
    TimeZone timeZone = Calendar.getInstance().getTimeZone();
    Date convertedDate = new Date(localDate.getTime() - timeZone.getRawOffset());

    if (timeZone.inDaylightTime(localDate)) {
        Date dstDate = new Date(convertedDate.getTime() - timeZone.getDSTSavings());

        if (timeZone.inDaylightTime(dstDate)) {
            return dstDate;
        }
    }

    return convertedDate;
}
 
Example 8
Source Project: cuba   File: TimeZones.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @return short string representation of the given time zone
 */
public String getDisplayNameShort(@Nullable TimeZone timeZone) {
    if (timeZone == null)
        return "";

    boolean dst = timeZone.inDaylightTime(timeSource.currentTimestamp());
    String name = timeZone.getDisplayName(dst, TimeZone.SHORT);

    if (AD_HOC_TZ_PATTERN.matcher(name).matches())
        return name;
    else
        return name + " (" + getDisplayOffset(timeZone) + ")";
}
 
Example 9
public void test_printText() {
    Random r = new Random();
    int N = 50;
    Locale[] locales = Locale.getAvailableLocales();
    Set<String> zids = ZoneRulesProvider.getAvailableZoneIds();
    ZonedDateTime zdt = ZonedDateTime.now();

    //System.out.printf("locale==%d, timezone=%d%n", locales.length, zids.size());
    while (N-- > 0) {
        zdt = zdt.withDayOfYear(r.nextInt(365) + 1)
                 .with(ChronoField.SECOND_OF_DAY, r.nextInt(86400));
        for (String zid : zids) {
            if (zid.equals("ROC") || zid.startsWith("Etc/GMT")) {
                continue;      // TBD: match jdk behavior?
            }
            zdt = zdt.withZoneSameLocal(ZoneId.of(zid));
            TimeZone tz = TimeZone.getTimeZone(zid);
            boolean isDST = tz.inDaylightTime(new Date(zdt.toInstant().toEpochMilli()));
            for (Locale locale : locales) {
                printText(locale, zdt, TextStyle.FULL, tz,
                        tz.getDisplayName(isDST, TimeZone.LONG, locale));
                printText(locale, zdt, TextStyle.SHORT, tz,
                        tz.getDisplayName(isDST, TimeZone.SHORT, locale));
            }
        }
    }
}
 
Example 10
public void test_printText() {
    Random r = RandomFactory.getRandom();
    int N = 8;
    Locale[] locales = Locale.getAvailableLocales();
    Set<String> zids = ZoneRulesProvider.getAvailableZoneIds();
    ZonedDateTime zdt = ZonedDateTime.now();

    //System.out.printf("locale==%d, timezone=%d%n", locales.length, zids.size());
    while (N-- > 0) {
        zdt = zdt.withDayOfYear(r.nextInt(365) + 1)
                 .with(ChronoField.SECOND_OF_DAY, r.nextInt(86400));
        for (String zid : zids) {
            if (zid.equals("ROC") || zid.startsWith("Etc/GMT")) {
                continue;      // TBD: match jdk behavior?
            }
            zdt = zdt.withZoneSameLocal(ZoneId.of(zid));
            TimeZone tz = TimeZone.getTimeZone(zid);
            boolean isDST = tz.inDaylightTime(new Date(zdt.toInstant().toEpochMilli()));
            for (Locale locale : locales) {
                String longDisplayName = tz.getDisplayName(isDST, TimeZone.LONG, locale);
                String shortDisplayName = tz.getDisplayName(isDST, TimeZone.SHORT, locale);
                if ((longDisplayName.startsWith("GMT+") && shortDisplayName.startsWith("GMT+"))
                        || (longDisplayName.startsWith("GMT-") && shortDisplayName.startsWith("GMT-"))) {
                    printText(locale, zdt, TextStyle.FULL, tz, tz.getID());
                    printText(locale, zdt, TextStyle.SHORT, tz, tz.getID());
                    continue;
                }
                printText(locale, zdt, TextStyle.FULL, tz,
                        tz.getDisplayName(isDST, TimeZone.LONG, locale));
                printText(locale, zdt, TextStyle.SHORT, tz,
                        tz.getDisplayName(isDST, TimeZone.SHORT, locale));
            }
        }
    }
}
 
Example 11
public void test_printText() {
    Random r = RandomFactory.getRandom();
    int N = 8;
    Locale[] locales = Locale.getAvailableLocales();
    Set<String> zids = ZoneRulesProvider.getAvailableZoneIds();
    ZonedDateTime zdt = ZonedDateTime.now();

    //System.out.printf("locale==%d, timezone=%d%n", locales.length, zids.size());
    while (N-- > 0) {
        zdt = zdt.withDayOfYear(r.nextInt(365) + 1)
                 .with(ChronoField.SECOND_OF_DAY, r.nextInt(86400));
        for (String zid : zids) {
            if (zid.equals("ROC") || zid.startsWith("Etc/GMT")) {
                continue;      // TBD: match jdk behavior?
            }
            zdt = zdt.withZoneSameLocal(ZoneId.of(zid));
            TimeZone tz = TimeZone.getTimeZone(zid);
            boolean isDST = tz.inDaylightTime(new Date(zdt.toInstant().toEpochMilli()));
            for (Locale locale : locales) {
                String longDisplayName = tz.getDisplayName(isDST, TimeZone.LONG, locale);
                String shortDisplayName = tz.getDisplayName(isDST, TimeZone.SHORT, locale);
                if ((longDisplayName.startsWith("GMT+") && shortDisplayName.startsWith("GMT+"))
                        || (longDisplayName.startsWith("GMT-") && shortDisplayName.startsWith("GMT-"))) {
                    printText(locale, zdt, TextStyle.FULL, tz, tz.getID());
                    printText(locale, zdt, TextStyle.SHORT, tz, tz.getID());
                    continue;
                }
                printText(locale, zdt, TextStyle.FULL, tz,
                        tz.getDisplayName(isDST, TimeZone.LONG, locale));
                printText(locale, zdt, TextStyle.SHORT, tz,
                        tz.getDisplayName(isDST, TimeZone.SHORT, locale));
            }
        }
    }
}
 
Example 12
Source Project: es6draft   File: TimeZoneInfo.java    License: MIT License 5 votes vote down vote up
@Override
public String getDisplayName(TimeZone tz, long date) {
    boolean daylightSavings = tz.inDaylightTime(new Date(date));
    if (!daylightSavings && tz.getOffset(date) != tz.getRawOffset()) {
        daylightSavings = tz.useDaylightTime();
    }
    return tz.getDisplayName(daylightSavings, TimeZone.SHORT, Locale.US);
}
 
Example 13
private JSONObject getIsDayLightSavingsTime(JSONArray options) throws GlobalizationError{
    JSONObject obj = new JSONObject();
    boolean dst = false;
    try{
        Date date = new Date((Long)options.getJSONObject(0).get(DATE));
        //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone();
        TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone());
        dst = tz.inDaylightTime(date); //get daylight savings data from date object and user timezone settings

        return obj.put("dst",dst);
    }catch(Exception ge){
        throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
    }
}
 
Example 14
Source Project: OpenRate   File: ConversionUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This function sees if a date is in Daylight Savings Time (DST)
 *
 * @param date The date the check
 * @return True if the date is in DST otherwise false
 */
public boolean getDateInDST( Date date )
{
   TimeZone tz = TimeZone.getDefault();

   boolean RetValue = tz.inDaylightTime(date);

   return RetValue;
}
 
Example 15
public void test_printText() {
    Random r = RandomFactory.getRandom();
    int N = 8;
    Locale[] locales = Locale.getAvailableLocales();
    Set<String> zids = ZoneRulesProvider.getAvailableZoneIds();
    ZonedDateTime zdt = ZonedDateTime.now();

    //System.out.printf("locale==%d, timezone=%d%n", locales.length, zids.size());
    while (N-- > 0) {
        zdt = zdt.withDayOfYear(r.nextInt(365) + 1)
                 .with(ChronoField.SECOND_OF_DAY, r.nextInt(86400));
        for (String zid : zids) {
            if (zid.equals("ROC") || zid.startsWith("Etc/GMT")) {
                continue;      // TBD: match jdk behavior?
            }
            zdt = zdt.withZoneSameLocal(ZoneId.of(zid));
            TimeZone tz = TimeZone.getTimeZone(zid);
            boolean isDST = tz.inDaylightTime(new Date(zdt.toInstant().toEpochMilli()));
            for (Locale locale : locales) {
                printText(locale, zdt, TextStyle.FULL, tz,
                        tz.getDisplayName(isDST, TimeZone.LONG, locale));
                printText(locale, zdt, TextStyle.SHORT, tz,
                        tz.getDisplayName(isDST, TimeZone.SHORT, locale));
            }
        }
    }
}
 
Example 16
public void test_printText() {
    Random r = new Random();
    int N = 50;
    Locale[] locales = Locale.getAvailableLocales();
    Set<String> zids = ZoneRulesProvider.getAvailableZoneIds();
    ZonedDateTime zdt = ZonedDateTime.now();

    //System.out.printf("locale==%d, timezone=%d%n", locales.length, zids.size());
    while (N-- > 0) {
        zdt = zdt.withDayOfYear(r.nextInt(365) + 1)
                 .with(ChronoField.SECOND_OF_DAY, r.nextInt(86400));
        for (String zid : zids) {
            if (zid.equals("ROC") || zid.startsWith("Etc/GMT")) {
                continue;      // TBD: match jdk behavior?
            }
            zdt = zdt.withZoneSameLocal(ZoneId.of(zid));
            TimeZone tz = TimeZone.getTimeZone(zid);
            boolean isDST = tz.inDaylightTime(new Date(zdt.toInstant().toEpochMilli()));
            for (Locale locale : locales) {
                printText(locale, zdt, TextStyle.FULL, tz,
                        tz.getDisplayName(isDST, TimeZone.LONG, locale));
                printText(locale, zdt, TextStyle.SHORT, tz,
                        tz.getDisplayName(isDST, TimeZone.SHORT, locale));
            }
        }
    }
}
 
Example 17
Source Project: phonegapbootcampsite   File: Globalization.java    License: MIT License 5 votes vote down vote up
private JSONObject getIsDayLightSavingsTime(JSONArray options) throws GlobalizationError{
    JSONObject obj = new JSONObject();
    boolean dst = false;
    try{
        Date date = new Date((Long)options.getJSONObject(0).get(DATE));
        //TimeZone tz = Calendar.getInstance(Locale.getDefault()).getTimeZone();
        TimeZone tz = TimeZone.getTimeZone(Time.getCurrentTimezone());
        dst = tz.inDaylightTime(date); //get daylight savings data from date object and user timezone settings

        return obj.put("dst",dst);
    }catch(Exception ge){
        throw new GlobalizationError(GlobalizationError.UNKNOWN_ERROR);
    }
}
 
Example 18
Source Project: RipplePower   File: ASN1GeneralizedTime.java    License: Apache License 2.0 5 votes vote down vote up
private String calculateGMTOffset()
{
    String sign = "+";
    TimeZone timeZone = TimeZone.getDefault();
    int offset = timeZone.getRawOffset();
    if (offset < 0)
    {
        sign = "-";
        offset = -offset;
    }
    int hours = offset / (60 * 60 * 1000);
    int minutes = (offset - (hours * 60 * 60 * 1000)) / (60 * 1000);

    try
    {
        if (timeZone.useDaylightTime() && timeZone.inDaylightTime(this.getDate()))
        {
            hours += sign.equals("+") ? 1 : -1;
        }
    }
    catch (ParseException e)
    {
        // we'll do our best and ignore daylight savings
    }

    return "GMT" + sign + convert(hours) + ":" + convert(minutes);
}
 
Example 19
Source Project: Openfire   File: LocaleUtils.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Returns the display name for a time zone. The display name is the name
 * specified by the Java TimeZone class for non-"en" locales or a friendly english
 * name for "en", with the addition of the GMT offset
 * for human readability.
 *
 * @param zoneID the time zone to get the name for.
 * @param locale the locale to use.
 * @return the display name for the time zone.
 */
public static String getTimeZoneName(String zoneID, Locale locale) {
    TimeZone zone = TimeZone.getTimeZone(zoneID);
    StringBuilder buf = new StringBuilder();
    // Add in the GMT part to the name. First, figure out the offset.
    int offset = zone.getRawOffset();
    if (zone.inDaylightTime(new Date()) && zone.useDaylightTime()) {
        offset += (int)JiveConstants.HOUR;
    }

    buf.append('(');
    if (offset < 0) {
        buf.append("GMT-");
    }
    else {
        buf.append("GMT+");
    }
    offset = Math.abs(offset);
    int hours = offset / (int)JiveConstants.HOUR;
    int minutes = (offset % (int)JiveConstants.HOUR) / (int)JiveConstants.MINUTE;
    buf.append(hours).append(':');
    if (minutes < 10) {
        buf.append('0').append(minutes);
    }
    else {
        buf.append(minutes);
    }
    buf.append(") ");

    // Use a friendly english timezone name if the locale is en, otherwise use the timezone id
    if ("en".equals(locale.getLanguage())) {
        String name = nameMap.get(zoneID);
        if (name == null) {
            name = zoneID;
        }

        buf.append(name);
    }
    else {
        buf.append(
                zone.getDisplayName(true, TimeZone.LONG, locale).replace('_', ' ').replace('/',
                        ' '));
    }

    return buf.toString();
}
 
Example 20
Source Project: cloudstack   File: ApiResponseHelper.java    License: Apache License 2.0 4 votes vote down vote up
public String getDateStringInternal(Date inputDate) {
    if (inputDate == null) {
        return null;
    }

    TimeZone tz = _usageSvc.getUsageTimezone();
    Calendar cal = Calendar.getInstance(tz);
    cal.setTime(inputDate);

    StringBuilder sb = new StringBuilder(32);
    sb.append(cal.get(Calendar.YEAR)).append('-');

    int month = cal.get(Calendar.MONTH) + 1;
    if (month < 10) {
        sb.append('0');
    }
    sb.append(month).append('-');

    int day = cal.get(Calendar.DAY_OF_MONTH);
    if (day < 10) {
        sb.append('0');
    }
    sb.append(day);

    sb.append("'T'");

    int hour = cal.get(Calendar.HOUR_OF_DAY);
    if (hour < 10) {
        sb.append('0');
    }
    sb.append(hour).append(':');

    int minute = cal.get(Calendar.MINUTE);
    if (minute < 10) {
        sb.append('0');
    }
    sb.append(minute).append(':');

    int seconds = cal.get(Calendar.SECOND);
    if (seconds < 10) {
        sb.append('0');
    }
    sb.append(seconds);

    double offset = cal.get(Calendar.ZONE_OFFSET);
    if (tz.inDaylightTime(inputDate)) {
        offset += (1.0 * tz.getDSTSavings()); // add the timezone's DST
        // value (typically 1 hour
        // expressed in milliseconds)
    }

    offset = offset / (1000d * 60d * 60d);
    int hourOffset = (int)offset;
    double decimalVal = Math.abs(offset) - Math.abs(hourOffset);
    int minuteOffset = (int)(decimalVal * 60);

    if (hourOffset < 0) {
        if (hourOffset > -10) {
            sb.append("-0");
        } else {
            sb.append('-');
        }
        sb.append(Math.abs(hourOffset));
    } else {
        if (hourOffset < 10) {
            sb.append("+0");
        } else {
            sb.append("+");
        }
        sb.append(hourOffset);
    }

    sb.append(':');

    if (minuteOffset == 0) {
        sb.append("00");
    } else if (minuteOffset < 10) {
        sb.append('0').append(minuteOffset);
    } else {
        sb.append(minuteOffset);
    }

    return sb.toString();
}