Java Code Examples for java.text.SimpleDateFormat#setTimeZone()

The following examples show how to use java.text.SimpleDateFormat#setTimeZone() . 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 File: DateUtil.java    From ALLGO with Apache License 2.0 6 votes vote down vote up
public static String saveDate(String time1 , String source ,String result) {
	String str = "";
	if(!time1.equals("")){
		SimpleDateFormat sf = new SimpleDateFormat(source, Locale.ENGLISH);
		sf.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
		Date date = null;
		try {
			date = sf.parse(time1);
		} catch (ParseException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		DateFormat sdf = new SimpleDateFormat(result, Locale.ENGLISH);
		sdf.setTimeZone(TimeZone.getTimeZone("GMT+08:00")); // 设置时区为GMT+08:00 
		    str = sdf.format(date);
	}
	return str;
}
 
Example 2
Source File: WeatherPagerAdapter.java    From privacy-friendly-weather with GNU General Public License v3.0 6 votes vote down vote up
public CharSequence getPageTitleForActionBar(int position) {

        int zoneseconds=0;
        //fallback to last time the weather data was updated
        long time = lastUpdateTime;
        int currentCityId = cities.get(position).getCityId();
        //search for current city
        for(CurrentWeatherData weatherData : currentWeathers) {
            if(weatherData.getCity_id() == currentCityId) {
                //set time to last update time for the city and zoneseconds to UTC difference (in seconds)
                time = weatherData.getTimestamp();
                zoneseconds += weatherData.getTimeZoneSeconds();
                break;
            }
        }
        //for formatting into time respective to UTC/GMT
        SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm");
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        Date updateTime = new Date((time+zoneseconds)*1000L);
        return String.format("%s (%s)", getPageTitle(position), dateFormat.format(updateTime));
    }
 
Example 3
Source File: Commentator.java    From JianDan with Apache License 2.0 6 votes vote down vote up
@Override
public int compareTo(Object another) {

    String anotherTimeString = ((Commentator) another).getCreated_at().replace("T", " ");
    anotherTimeString = anotherTimeString.substring(0, anotherTimeString.indexOf("+"));

    String thisTimeString = getCreated_at().replace("T", " ");
    thisTimeString = thisTimeString.substring(0, thisTimeString.indexOf("+"));

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT+08"));

    try {
        Date anotherDate = simpleDateFormat.parse(anotherTimeString);
        Date thisDate = simpleDateFormat.parse(thisTimeString);
        return -thisDate.compareTo(anotherDate);
    } catch (ParseException e) {
        e.printStackTrace();
        return 0;
    }
}
 
Example 4
Source File: LookupSnapshotBuildJob.java    From kylin with Apache License 2.0 6 votes vote down vote up
private static LookupSnapshotBuildJob initJob(CubeInstance cube, String tableName, String submitter,
        KylinConfig kylinConfig) {
    List<ProjectInstance> projList = ProjectManager.getInstance(kylinConfig).findProjects(cube.getType(),
            cube.getName());
    if (projList == null || projList.size() == 0) {
        throw new RuntimeException("Cannot find the project containing the cube " + cube.getName() + "!!!");
    } else if (projList.size() >= 2) {
        String msg = "Find more than one project containing the cube " + cube.getName()
                + ". It does't meet the uniqueness requirement!!! ";
        throw new RuntimeException(msg);
    }

    LookupSnapshotBuildJob result = new LookupSnapshotBuildJob();
    SimpleDateFormat format = new SimpleDateFormat("z yyyy-MM-dd HH:mm:ss", Locale.ROOT);
    format.setTimeZone(TimeZone.getTimeZone(kylinConfig.getTimeZone()));
    result.setDeployEnvName(kylinConfig.getDeployEnv());
    result.setProjectName(projList.get(0).getName());
    CubingExecutableUtil.setCubeName(cube.getName(), result.getParams());
    result.setName(JOB_TYPE + " CUBE - " + cube.getName() + " - " + " TABLE - " + tableName + " - "
            + format.format(new Date(System.currentTimeMillis())));
    result.setSubmitter(submitter);
    result.setNotifyList(cube.getDescriptor().getNotifyList());
    return result;
}
 
Example 5
Source File: gson_common_deserializer.java    From AndroidWallet with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Date deserialize(JsonElement json,
                        Type typeOfT,
                        JsonDeserializationContext context) throws JsonParseException {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));

    try {
        Date dateResult = simpleDateFormat.parse(json.getAsString());

        return dateResult;
    } catch (ParseException e) {
        e.printStackTrace();
        throw new JsonParseException(e.getMessage() + json.getAsString());
    }
}
 
Example 6
Source File: DateUtils.java    From restcommander with Apache License 2.0 5 votes vote down vote up
public static String getDateTimeStrConcise(Date d) {
	if (d == null)
		return "";

	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSSZ");
	//20140317: force the timezone to avoid PLUS 
	sdf.setTimeZone(TimeZone.getTimeZone(VarUtils.STR_LOG_TIME_ZONE));
	String str = sdf.format(d);
	return str;
}
 
Example 7
Source File: StaticFileServerHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the "date" and "cache" headers for the HTTP Response.
 *
 * @param response    The HTTP response object.
 * @param fileToCache File to extract the modification timestamp from.
 */
public static void setDateAndCacheHeaders(HttpResponse response, File fileToCache) {
	SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
	dateFormatter.setTimeZone(GMT_TIMEZONE);

	// date header
	Calendar time = new GregorianCalendar();
	response.headers().set(DATE, dateFormatter.format(time.getTime()));

	// cache headers
	time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
	response.headers().set(EXPIRES, dateFormatter.format(time.getTime()));
	response.headers().set(CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
	response.headers().set(LAST_MODIFIED, dateFormatter.format(new Date(fileToCache.lastModified())));
}
 
Example 8
Source File: PeriodAxis.java    From SIMVA-SoS with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new axis.
 *
 * @param label  the axis label (<code>null</code> permitted).
 * @param first  the first time period in the axis range
 *               (<code>null</code> not permitted).
 * @param last  the last time period in the axis range
 *              (<code>null</code> not permitted).
 * @param timeZone  the time zone (<code>null</code> not permitted).
 * @param locale  the locale (<code>null</code> not permitted).
 *
 * @since 1.0.13
 */
public PeriodAxis(String label, RegularTimePeriod first,
        RegularTimePeriod last, TimeZone timeZone, Locale locale) {
    super(label, null);
    ParamChecks.nullNotPermitted(timeZone, "timeZone");
    ParamChecks.nullNotPermitted(locale, "locale");
    this.first = first;
    this.last = last;
    this.timeZone = timeZone;
    this.locale = locale;
    this.calendar = Calendar.getInstance(timeZone, locale);
    this.first.peg(this.calendar);
    this.last.peg(this.calendar);
    this.autoRangeTimePeriodClass = first.getClass();
    this.majorTickTimePeriodClass = first.getClass();
    this.minorTickMarksVisible = false;
    this.minorTickTimePeriodClass = RegularTimePeriod.downsize(
            this.majorTickTimePeriodClass);
    setAutoRange(true);
    this.labelInfo = new PeriodAxisLabelInfo[2];
    SimpleDateFormat df0 = new SimpleDateFormat("MMM", locale);
    df0.setTimeZone(timeZone);
    this.labelInfo[0] = new PeriodAxisLabelInfo(Month.class, df0);
    SimpleDateFormat df1 = new SimpleDateFormat("yyyy", locale);
    df1.setTimeZone(timeZone);
    this.labelInfo[1] = new PeriodAxisLabelInfo(Year.class, df1);
}
 
Example 9
Source File: SimpleDateFormatTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test2038() {
    SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss yyyy", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));

    assertEquals("Sun Nov 24 17:31:44 1833",
            format.format(new Date(((long) Integer.MIN_VALUE + Integer.MIN_VALUE) * 1000L)));
    assertEquals("Fri Dec 13 20:45:52 1901",
            format.format(new Date(Integer.MIN_VALUE * 1000L)));
    assertEquals("Thu Jan 01 00:00:00 1970",
            format.format(new Date(0L)));
    assertEquals("Tue Jan 19 03:14:07 2038",
            format.format(new Date(Integer.MAX_VALUE * 1000L)));
    assertEquals("Sun Feb 07 06:28:16 2106",
            format.format(new Date((2L + Integer.MAX_VALUE + Integer.MAX_VALUE) * 1000L)));
}
 
Example 10
Source File: JoinedFlatTable.java    From Kylin with Apache License 2.0 5 votes vote down vote up
private static String formatDateTimeInWhereClause(long datetime) {
    SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    f.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = new Date(datetime);
    String str = f.format(date);
    // note "2014-10-01" >= "2014-10-01 00:00:00" is FALSE
    return StringUtil.dropSuffix(str, " 00:00:00");
}
 
Example 11
Source File: DateTimeAdapter.java    From SeaCloudsPlatform with Apache License 2.0 5 votes vote down vote up
@Override
public Date unmarshal(String dateAsString) throws Exception {
    Date date = null;
    try{
        SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
        formatter.setTimeZone(TimeZone.getTimeZone(unmarshallTimezone));
        date = formatter.parse(dateAsString);
    }catch(Throwable t){
        throw new ParserException(
                "Date " + dateAsString + " couldn't be unmarshal with " + dateFormat + 
                " and timezone "+unmarshallTimezone, t);
    }
    logger.debug(date +"{} has been unmarshalled to {}", dateAsString, date);
    return date;
}
 
Example 12
Source File: DateAdapterTest.java    From recheck with GNU Affero General Public License v3.0 5 votes vote down vote up
@Test
public void can_parse_default_dateFormat_from_before_refactoring() {
	final Date origin = new Date();
	final SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss Z", Locale.GERMANY );
	dateFormat.setTimeZone( TimeZone.getTimeZone( "GMT+2" ) );
	final String defaultdateFormatBeforeRefactoring = dateFormat.format( origin );

	assertThat( dateAdapter.unmarshal( defaultdateFormatBeforeRefactoring ) ).isInSameSecondAs( origin );
}
 
Example 13
Source File: DateUtil.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
static String toFormatNoZone(final long timestamp) {
    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
    format.setTimeZone(TimeZone.getDefault());
    return format.format(timestamp);
}
 
Example 14
Source File: LetvLogApiTool.java    From letv with Apache License 2.0 4 votes vote down vote up
private static String getTimeStamp() {
    SimpleDateFormat formatTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    formatTime.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
    return formatTime.format(new Date(System.currentTimeMillis()));
}
 
Example 15
Source File: MockHttpServletResponse.java    From java-technology-stack with MIT License 4 votes vote down vote up
private DateFormat newDateFormat() {
	SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT, Locale.US);
	dateFormat.setTimeZone(GMT);
	return dateFormat;
}
 
Example 16
Source File: Bug6530336.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public static void main(String[] args) throws Exception {
    Locale defaultLocale = Locale.getDefault();
    TimeZone defaultTimeZone = TimeZone.getDefault();

    boolean err = false;

    try {
        Locale locales[] = Locale.getAvailableLocales();
        TimeZone timezone_LA = TimeZone.getTimeZone("America/Los_Angeles");
        TimeZone.setDefault(timezone_LA);

        TimeZone timezones[] = {
            TimeZone.getTimeZone("America/New_York"),
            TimeZone.getTimeZone("America/Denver"),
        };

        String[] expected = {
            "Sun Jul 15 12:00:00 PDT 2007",
            "Sun Jul 15 14:00:00 PDT 2007",
        };

        Date[] dates = new Date[2];

        for (int i = 0; i < locales.length; i++) {
            Locale locale = locales[i];
            if (!TestUtils.usesGregorianCalendar(locale)) {
                continue;
            }

            Locale.setDefault(locale);

            for (int j = 0; j < timezones.length; j++) {
                Calendar cal = Calendar.getInstance(timezones[j]);
                cal.set(2007, 6, 15, 15, 0, 0);
                dates[j] = cal.getTime();
            }

            SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");

            for (int j = 0; j < timezones.length; j++) {
                sdf.setTimeZone(timezones[j]);
                String date = sdf.format(dates[j]);
                sdf.setTimeZone(timezone_LA);
                String date_LA = sdf.parse(date).toString();

                if (!expected[j].equals(date_LA)) {
                    System.err.println("Got wrong Pacific time (" +
                        date_LA + ") for (" + date + ") in " + locale +
                        " in " + timezones[j] +
                        ".\nExpected=" + expected[j]);
                    err = true;
                }
            }
        }
    }
    catch (Exception e) {
        e.printStackTrace();
        err = true;
    }
    finally {
        Locale.setDefault(defaultLocale);
        TimeZone.setDefault(defaultTimeZone);

        if (err) {
            throw new RuntimeException("Failed.");
        }
    }
}
 
Example 17
Source File: TestDateFormatCache.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug54044() throws Exception {

    final String timeFormat = "dd-MMM-yyyy HH:mm:ss";
    final int cacheSize = 10;

    SimpleDateFormat sdf = new SimpleDateFormat(timeFormat, Locale.US);
    sdf.setTimeZone(TimeZone.getDefault());

    DateFormatCache dfc = new DateFormatCache(cacheSize, timeFormat, null);

    // Get dfc.cache.cache field
    Object dfcCache;
    Field dfcCacheArray;
    {
        Field dfcCacheField = dfc.getClass().getDeclaredField("cache");
        dfcCacheField.setAccessible(true);
        dfcCache = dfcCacheField.get(dfc);
        dfcCacheArray = dfcCache.getClass().getDeclaredField("cache");
        dfcCacheArray.setAccessible(true);
    }

    // Create an array to hold the expected values
    String[] expected = new String[cacheSize];

    // Fill the cache & populate the expected values
    for (int secs = 0; secs < (cacheSize); secs++) {
        dfc.getFormat(secs * 1000);
        expected[secs] = generateExpected(sdf, secs);
    }
    Assert.assertArrayEquals(expected,
            (String[]) dfcCacheArray.get(dfcCache));

    // Cause the cache to roll-around by one and then confirm
    dfc.getFormat(cacheSize * 1000);
    expected[0] = generateExpected(sdf, cacheSize);
    Assert.assertArrayEquals(expected,
            (String[]) dfcCacheArray.get(dfcCache));

    // Jump 2 ahead and then confirm (skipped value should be null)
    dfc.getFormat((cacheSize + 2) * 1000);
    expected[1] = null;
    expected[2] = generateExpected(sdf, cacheSize + 2);
    Assert.assertArrayEquals(expected,
            (String[]) dfcCacheArray.get(dfcCache));

    // Back 1 to fill in the gap
    dfc.getFormat((cacheSize + 1) * 1000);
    expected[1] = generateExpected(sdf, cacheSize + 1);
    Assert.assertArrayEquals(expected,
            (String[]) dfcCacheArray.get(dfcCache));

    // Return to 1 and confirm skipped value is null
    dfc.getFormat(1 * 1000);
    expected[1] = generateExpected(sdf, 1);
    expected[2] = null;
    Assert.assertArrayEquals(expected,
            (String[]) dfcCacheArray.get(dfcCache));

    // Go back one further
    dfc.getFormat(0);
    expected[0] = generateExpected(sdf, 0);
    Assert.assertArrayEquals(expected,
            (String[]) dfcCacheArray.get(dfcCache));

    // Jump ahead far enough that the entire cache will need to be cleared
    dfc.getFormat(42 * 1000);
    for (int i = 0; i < cacheSize; i++) {
        expected[i] = null;
    }
    expected[0] = generateExpected(sdf, 42);
    Assert.assertArrayEquals(expected,
            (String[]) dfcCacheArray.get(dfcCache));
}
 
Example 18
Source File: DateUtil.java    From xDrip with GNU General Public License v3.0 4 votes vote down vote up
static String toFormatAsUTC(final long timestamp) {
    final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'0000Z'", Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    return format.format(timestamp);
}
 
Example 19
Source File: ScheduleUtil.java    From garoon-google with MIT License 4 votes vote down vote up
private static Date parseWhenDatetime(String source, TimeZone timezone) throws ParseException
{
	SimpleDateFormat formatter = new SimpleDateFormat("yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'");
	formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
	return formatter.parse(source);
}
 
Example 20
Source File: DateTimeAdapter.java    From nifi with Apache License 2.0 4 votes vote down vote up
@Override
public String marshal(Date date) throws Exception {
    final SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT, Locale.US);
    formatter.setTimeZone(TimeZone.getDefault());
    return formatter.format(date);
}