Java Code Examples for java.util.TimeZone
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
/** * Get the real time from the server * @author Lathanael * @param gmt The wanted GMT offset * @return serverTime Represents the time read from the server */ public static Date getServerRealTime(final String gmt){ Date serverTime; final TimeZone tz=TimeZone.getTimeZone(gmt); final Calendar cal=Calendar.getInstance(tz); cal.setTime(new Date()); serverTime=cal.getTime(); return serverTime; }
Example 2
From project amplafi-sworddance, under directory /src/test/java/com/sworddance/scheduling/.
Source file: FakeTimeServerImpl.java

public void setBaseTime(int year,int month,int day,int hour,int minute,int second,String timezoneId){ Calendar date=Calendar.getInstance(); date.clear(); date.set(year,month,day,hour,minute,second); if (timezoneId != null) { TimeZone value=TimeZone.getTimeZone(timezoneId); date.setTimeZone(value); } setBaseTime(date); }
Example 3
From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/.
Source file: DateTimeSettings.java

private String getTimeZoneText(){ TimeZone tz=java.util.Calendar.getInstance().getTimeZone(); boolean daylight=tz.inDaylightTime(new Date()); StringBuilder sb=new StringBuilder(); sb.append(formatOffset(tz.getRawOffset() + (daylight ? tz.getDSTSavings() : 0))).append(", ").append(tz.getDisplayName(daylight,TimeZone.LONG)); return sb.toString(); }
Example 4
private void sendEmail(String body){ Intent sendIntent=new Intent(Intent.ACTION_SEND); SimpleDateFormat df1=new SimpleDateFormat("EEE MMM dd HH:mm:ss ",Locale.US); SimpleDateFormat df2=new SimpleDateFormat(" yyyy",Locale.US); Date ts=new Date(); TimeZone tz=TimeZone.getDefault(); String subject=String.format("Bug Report on %s%s%s",df1.format(ts),tz.getID(),df2.format(ts)); sendIntent.putExtra(Intent.EXTRA_EMAIL,new String[]{getString(R.string.error_email)}); sendIntent.putExtra(Intent.EXTRA_TEXT,body); sendIntent.putExtra(Intent.EXTRA_SUBJECT,subject); sendIntent.setType("message/rfc822"); startActivity(Intent.createChooser(sendIntent,"Send Error Report")); }
Example 5
From project asterisk-java, under directory /src/test/java/org/asteriskjava/util/.
Source file: DateUtilTest.java

@Test public void testGetStartTimeAsDateWithTimeZone(){ final TimeZone tz=TimeZone.getTimeZone("GMT+2"); final Date result=DateUtil.parseDateTime(dateString,tz); assertEquals(1148032488000L,result.getTime()); assertEquals("Fri May 19 09:54:48 GMT 2006",result.toString()); }
Example 6
From project b3log-solo, under directory /core/src/main/java/org/b3log/solo/util/.
Source file: TimeZones.java

/** * Gets the current date with the specified time zone id. * @param timeZoneId the specified time zone id * @return date */ public static Date getTime(final String timeZoneId){ final TimeZone timeZone=TimeZone.getTimeZone(timeZoneId); final TimeZone defaultTimeZone=TimeZone.getDefault(); TimeZone.setDefault(timeZone); final Date ret=new Date(); TimeZone.setDefault(defaultTimeZone); return ret; }
Example 7
From project baseunits, under directory /src/main/java/jp/xet/baseunits/time/.
Source file: CalendarDate.java

/** * ?????????????????@link CalendarDate}??????????????????? * @param dateString ????????????? * @param pattern ????????????? * @return {@link CalendarDate} * @throws ParseException ??????????????????? * @throws IllegalArgumentException ?????@code null}????????? * @since 1.0 */ public static CalendarDate parse(String dateString,String pattern) throws ParseException { Validate.notNull(dateString); Validate.notNull(pattern); TimeZone arbitraryZone=TimeZone.getTimeZone("Universal"); TimePoint point=TimePoint.parse(dateString,pattern,arbitraryZone); return CalendarDate.from(point,arbitraryZone); }
Example 8
From project cotopaxi-core, under directory /src/main/java/br/octahedron/util/.
Source file: DateUtil.java

/** */ private static void load(){ String offset=property(TIMEZONE); if (offset != null) { int offsetMillis=parseInt(offset) * 36 * 1000; TimeZone systemTz=new SimpleTimeZone(offsetMillis,"Cotopaxi/System"); defaultTimeZone(systemTz); } loaded=true; }
Example 9
From project creamed_glacier_app_settings, under directory /src/com/android/settings/.
Source file: ZonePicker.java

@Override public void onListItemClick(ListView listView,View v,int position,long id){ final Map<?,?> map=(Map<?,?>)listView.getItemAtPosition(position); final String tzId=(String)map.get(KEY_ID); final Activity activity=getActivity(); final AlarmManager alarm=(AlarmManager)activity.getSystemService(Context.ALARM_SERVICE); alarm.setTimeZone(tzId); final TimeZone tz=TimeZone.getTimeZone(tzId); if (mListener != null) { mListener.onZoneSelected(tz); } else { getActivity().onBackPressed(); } }
Example 10
From project dcm4che, under directory /dcm4che-core/src/main/java/org/dcm4che/data/.
Source file: Attributes.java

public Object setDateRange(String privateCreator,int tag,VR vr,DateRange range){ TimeZone tz=getTimeZone(); String start=range.getStartDate() != null ? (String)vr.toValue(new Date[]{range.getStartDate()},tz) : ""; String end=range.getEndDate() != null ? (String)vr.toValue(new Date[]{range.getEndDate()},tz) : ""; return set(privateCreator,tag,vr,start.equals(end) ? start : (start + '-' + end)); }
Example 11
From project agile, under directory /agile-framework/src/main/java/org/headsupdev/agile/framework/.
Source file: HeadsUpActivator.java

/** * Called whenever the OSGi framework starts our bundle */ public void start(BundleContext bc) throws Exception { String defaultTimeZoneId=System.getProperty("agile.runtime.timezone"); if (defaultTimeZoneId != null) { Manager.getLogger(getClass().getName()).info("Detected system timezone " + defaultTimeZoneId); TimeZone defaultTimeZone=TimeZone.getTimeZone(defaultTimeZoneId); Manager.getStorageInstance().getGlobalConfiguration().setDefaultTimeZone(defaultTimeZone); } Manager.getLogger(getClass().getName()).info("Default timezone set to " + Manager.getStorageInstance().getGlobalConfiguration().getDefaultTimeZone().getID()); Dictionary props=new Hashtable(); props.put("alias","/"); props.put("servlet-name","Wicket Servlet"); bc.registerService(Servlet.class.getName(),new HeadsUpServlet(),props); props=new Hashtable(); String[] urls={"/*"}; props.put("filter-name","Wicket Filter"); props.put("urlPatterns",urls); bc.registerService(Filter.class.getName(),new HeadsUpFilter(),props); props=new Hashtable(); props.put("alias","/repository/*"); bc.registerService(Servlet.class.getName(),new RepositoryServlet(),props); props=new Hashtable(); props.put("alias","/favicon.ico"); bc.registerService(Servlet.class.getName(),new FaviconServlet(),props); HomeApplication homeApp=new HomeApplication(); homeApp.setContext(bc); props=new Properties(); bc.registerService(Application.class.getName(),homeApp,props); DefaultErrorPageMapping error=new DefaultErrorPageMapping(); error.setError("404"); error.setLocation("/filenotfound"); bc.registerService(ErrorPageMapping.class.getName(),error,null); System.out.println("Started version " + Manager.getStorageInstance().getGlobalConfiguration().getBuildVersion() + " at "+ Manager.getStorageInstance().getGlobalConfiguration().getBaseUrl()); webTracker=new WebTracker(bc); webTracker.open(); appTracker=new AppTracker(bc); appTracker.open(); }
Example 12
From project android_packages_apps_Exchange, under directory /src/com/android/exchange/utility/.
Source file: CalendarUtilities.java

/** * Given a String as directly read from EAS, returns a TimeZone corresponding to that String * @param timeZoneString the String read from the server * @param precision the number of milliseconds of precision in TimeZone determination * @return the TimeZone, or TimeZone.getDefault() if not found */ @VisibleForTesting static TimeZone tziStringToTimeZone(String timeZoneString,int precision){ TimeZone timeZone=sTimeZoneCache.get(timeZoneString); if (timeZone != null) { if (Eas.USER_LOG) { ExchangeService.log(TAG," Using cached TimeZone " + timeZone.getID()); } } else { timeZone=tziStringToTimeZoneImpl(timeZoneString,precision); if (timeZone == null) { ExchangeService.alwaysLog("TimeZone not found using default: " + timeZoneString); timeZone=TimeZone.getDefault(); } sTimeZoneCache.put(timeZoneString,timeZone); } return timeZone; }
Example 13
From project apps-for-android, under directory /AndroidGlobalTime/src/com/android/globaltime/.
Source file: City.java

/** * Returns the cities, ordered by offset, accounting for summer/daylight savings time. This requires reading the entire time zone database behind the scenes. */ public static City[] getCitiesByOffset(){ City[] ocities=cities.values().toArray(new City[0]); Arrays.sort(ocities,new Comparator<City>(){ public int compare( City c1, City c2){ long now=System.currentTimeMillis(); TimeZone tz1=c1.getTimeZone(); TimeZone tz2=c2.getTimeZone(); int off1=tz1.getOffset(now); int off2=tz2.getOffset(now); if (off1 == off2) { float dlat=c2.getLatitude() - c1.getLatitude(); if (dlat < 0.0f) return -1; if (dlat > 0.0f) return 1; return 0; } return off1 - off2; } } ); return ocities; }
Example 14
From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/casemodule/.
Source file: AddImageVisualPanel1.java

/** * Creates the drop down list for the time zones and then makes the local machine time zones to be selected. */ public void createTimeZoneList(){ String[] ids=SimpleTimeZone.getAvailableIDs(); for ( String id : ids) { TimeZone zone=TimeZone.getTimeZone(id); int offset=zone.getRawOffset() / 1000; int hour=offset / 3600; int minutes=(offset % 3600) / 60; String item=String.format("(GMT%+d:%02d) %s",hour,minutes,id); timeZoneComboBox.addItem(item); } TimeZone thisTimeZone=Calendar.getInstance().getTimeZone(); int thisOffset=thisTimeZone.getRawOffset() / 1000; int thisHour=thisOffset / 3600; int thisMinutes=(thisOffset % 3600) / 60; String formatted=String.format("(GMT%+d:%02d) %s",thisHour,thisMinutes,thisTimeZone.getID()); timeZoneComboBox.setSelectedItem(formatted); }
Example 15
From project CalendarPortlet, under directory /src/test/java/org/jasig/portlet/calendar/mvc/controller/.
Source file: AjaxCalendarControllerTest.java

@Test public void testAddLongEventToDateMap() throws IOException, URISyntaxException, ParseException { TimeZone tz=TimeZone.getTimeZone("America/Los Angeles"); DateFormat df=new SimpleDateFormat("EEEE MMMM d"); df.setTimeZone(tz); Calendar cal=Calendar.getInstance(tz); cal.set(Calendar.YEAR,2011); cal.set(Calendar.MONTH,0); cal.set(Calendar.DATE,3); cal.set(Calendar.HOUR_OF_DAY,4); cal.set(Calendar.MINUTE,0); cal.set(Calendar.SECOND,0); cal.set(Calendar.MILLISECOND,0); Date start=cal.getTime(); cal.add(Calendar.DATE,1); Date periodStart=cal.getTime(); cal.add(Calendar.DATE,1); Date end=cal.getTime(); Period period=new Period(new DateTime(periodStart),new DateTime(end)); VEvent event=new VEvent(new DateTime(start),new DateTime(end),"Test Event"); List<CalendarDisplayEvent> events=new ArrayList<CalendarDisplayEvent>(); }
Example 16
From project core_4, under directory /api/src/test/java/org/ajax4jsf/javascript/.
Source file: ScriptUtilsTest.java

@Test public void testTimezoneSerialization() throws Exception { TimeZone utcPlusTwoTZ=TimeZone.getTimeZone("GMT+02:00"); String serializedUTCPlusTwoTZ=dehydrate(ScriptUtils.toScript(utcPlusTwoTZ)); assertThat(serializedUTCPlusTwoTZ,StringContains.containsString("\"DSTSavings\":0")); assertThat(serializedUTCPlusTwoTZ,StringContains.containsString("\"ID\":\"GMT+02:00\"")); assertThat(serializedUTCPlusTwoTZ,StringContains.containsString("\"rawOffset\":7200000")); TimeZone pstTimeZone=TimeZone.getTimeZone("PST"); String serializedPSTTimeZone=dehydrate(ScriptUtils.toScript(pstTimeZone)); assertThat(serializedPSTTimeZone,StringContains.containsString("\"ID\":\"PST\"")); assertThat(serializedPSTTimeZone,StringContains.containsString("\"rawOffset\":-28800000")); TimeZone sfTimeZone=TimeZone.getTimeZone("America/New_York"); String serializedSFTimeZone=dehydrate(ScriptUtils.toScript(sfTimeZone)); assertThat(serializedSFTimeZone,StringContains.containsString("\"ID\":\"America\\/New_York\"")); assertThat(serializedSFTimeZone,StringContains.containsString("\"rawOffset\":-18000000")); }
Example 17
From project dccsched, under directory /src/com/underhilllabs/dccsched/ui/.
Source file: ScheduleActivity.java

private void setupBlocksTab(String tag,long startMillis){ final TabHost host=getTabHost(); final long endMillis=startMillis + DateUtils.DAY_IN_MILLIS; final Uri blocksBetweenDirUri=Blocks.buildBlocksBetweenDirUri(startMillis,endMillis); final Intent intent=new Intent(Intent.ACTION_VIEW,blocksBetweenDirUri); intent.addCategory(Intent.CATEGORY_TAB); intent.putExtra(BlocksActivity.EXTRA_TIME_START,startMillis); intent.putExtra(BlocksActivity.EXTRA_TIME_END,endMillis); TimeZone.setDefault(UIUtils.CONFERENCE_TIME_ZONE); final String label=DateUtils.formatDateTime(this,startMillis,TIME_FLAGS); host.addTab(host.newTabSpec(tag).setIndicator(buildIndicator(label)).setContent(intent)); }
Example 18
From project AdServing, under directory /modules/server/adserver/src/main/java/net/mad/ads/server/utils/request/.
Source file: RequestHelper.java

private static void addTimeCondition(HttpServletRequest request,AdRequest adRequest){ String strOffSet=request.getParameter(RequestHelper.offset); int offset=Integer.parseInt(strOffSet); offset=offset * 60000; String[] ids=TimeZone.getAvailableIDs(offset); Calendar temp=Calendar.getInstance(); temp.setTimeZone(TimeZone.getTimeZone(ids[0])); DateFormat dateFormat=new SimpleDateFormat("yyyyMMdd"); DateFormat timeFormat=new SimpleDateFormat("HHmm"); adRequest.setTime(timeFormat.format(temp.getTime())); adRequest.setDate(dateFormat.format(temp.getTime())); adRequest.setDay(Day.getDayForJava(temp.get(Calendar.DAY_OF_WEEK))); }
Example 19
From project aether-core, under directory /aether-impl/src/test/java/org/eclipse/aether/internal/impl/.
Source file: DefaultUpdateCheckManagerTest.java

@Test public void testCheckArtifactUpdatePolicyRequired() throws Exception { UpdateCheck<Artifact,ArtifactTransferException> check=newArtifactCheck(); check.setItem(artifact); check.setFile(artifact.getFile()); Calendar cal=Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.add(Calendar.DATE,-1); long lastUpdate=cal.getTimeInMillis(); artifact.getFile().setLastModified(lastUpdate); check.setLocalLastUpdated(lastUpdate); check.setPolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS); manager.checkArtifact(session,check); assertNull(check.getException()); assertTrue(check.isRequired()); check.setPolicy(RepositoryPolicy.UPDATE_POLICY_DAILY); manager.checkArtifact(session,check); assertNull(check.getException()); assertTrue(check.isRequired()); check.setPolicy(RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":60"); manager.checkArtifact(session,check); assertNull(check.getException()); assertTrue(check.isRequired()); }
Example 20
From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/model/manageData/.
Source file: ViewTools.java

public String getTimezone(){ String timezone=TimeZone.getDefault().getDisplayName(false,TimeZone.LONG); if (timezone.toLowerCase().equals("greenwich mean time")) { timezone="Europe/London"; } return timezone; }
Example 21
From project agraph-java-client, under directory /src/test/.
Source file: RepositoryConnectionTest.java

@SuppressWarnings("deprecation") @Test @Category(TestSuites.Broken.class) public void testXmlCalendarZ() throws Exception { String NS="http://example.org/rdf/"; int OFFSET=TimeZone.getDefault().getOffset(new Date(2007,Calendar.NOVEMBER,6).getTime()) / 1000 / 60; String SELECT_BY_DATE="SELECT ?s ?d WHERE { ?s <http://www.w3.org/1999/02/22-rdf-syntax-ns#value> ?d . FILTER (?d <= ?date) }"; DatatypeFactory data=DatatypeFactory.newInstance(); for (int i=1; i < 5; i++) { URI uri=vf.createURI(NS,"date" + i); XMLGregorianCalendar xcal=data.newXMLGregorianCalendar(); xcal.setYear(2000); xcal.setMonth(11); xcal.setDay(i * 2); testCon.add(uri,RDF.VALUE,vf.createLiteral(xcal)); URI uriz=vf.createURI(NS,"dateZ" + i); xcal=data.newXMLGregorianCalendar(); xcal.setYear(2007); xcal.setMonth(11); xcal.setDay(i * 2); xcal.setTimezone(OFFSET); testCon.add(uriz,RDF.VALUE,vf.createLiteral(xcal)); } XMLGregorianCalendar xcal=data.newXMLGregorianCalendar(); xcal.setYear(2007); xcal.setMonth(11); xcal.setDay(6); xcal.setTimezone(OFFSET); TupleQuery query=testCon.prepareTupleQuery(QueryLanguage.SPARQL,SELECT_BY_DATE); query.setBinding("date",vf.createLiteral(xcal)); TupleQueryResult result=query.evaluate(); List<BindingSet> list=new ArrayList<BindingSet>(); while (result.hasNext()) { list.add(result.next()); } assertEquals(7,list.size()); }
Example 22
From project Airports, under directory /src/com/nadmm/airports/utils/.
Source file: DataUtils.java

public static String getTimeZoneAsString(TimeZone tz){ Date now=new Date(); String tzName=tz.getDisplayName(tz.inDaylightTime(now),TimeZone.SHORT); DateFormat tzFormat=new SimpleDateFormat("'(UTC'Z')'"); tzFormat.setTimeZone(tz); return String.format("%s %s",tzName,tzFormat.format(now)); }
Example 23
From project AlarmApp-Android, under directory /src/org/alarmapp/util/.
Source file: DateUtil.java

private static SimpleDateFormat getFormatter(){ if (formatter == null) { formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); formatter.setTimeZone(TimeZone.getTimeZone("GMT")); } return formatter; }
Example 24
From project AmDroid, under directory /httpclientandroidlib/src/ch/boye/httpclientandroidlib/impl/cookie/.
Source file: DateUtils.java

/** * creates a {@link SimpleDateFormat} for the requested format string. * @param pattern a non-<code>null</code> format String according to {@link SimpleDateFormat}. The format is not checked against <code>null</code> since all paths go through {@link DateUtils}. * @return the requested format. This simple dateformat should not be usedto {@link SimpleDateFormat#applyPattern(String) apply} to adifferent pattern. */ public static SimpleDateFormat formatFor(String pattern){ SoftReference<Map<String,SimpleDateFormat>> ref=THREADLOCAL_FORMATS.get(); Map<String,SimpleDateFormat> formats=ref.get(); if (formats == null) { formats=new HashMap<String,SimpleDateFormat>(); THREADLOCAL_FORMATS.set(new SoftReference<Map<String,SimpleDateFormat>>(formats)); } SimpleDateFormat format=formats.get(pattern); if (format == null) { format=new SimpleDateFormat(pattern,Locale.US); format.setTimeZone(TimeZone.getTimeZone("GMT")); formats.put(pattern,format); } return format; }
Example 25
From project Amoeba-for-Aladdin, under directory /src/java/com/meidusa/amoeba/util/.
Source file: DateTimeUtils.java

private static long getTime(boolean lenient,TimeZone tz,int year,int month,int day,int hour,int minute,int second,boolean setMillis,int nano){ Calendar c; if (tz == null) { c=Calendar.getInstance(); } else { c=Calendar.getInstance(tz); } c.setLenient(lenient); if (year <= 0) { c.set(Calendar.ERA,GregorianCalendar.BC); c.set(Calendar.YEAR,1 - year); } else { c.set(Calendar.YEAR,year); } c.set(Calendar.MONTH,month - 1); c.set(Calendar.DAY_OF_MONTH,day); c.set(Calendar.HOUR_OF_DAY,hour); c.set(Calendar.MINUTE,minute); c.set(Calendar.SECOND,second); if (setMillis) { c.set(Calendar.MILLISECOND,nano / 1000000); } return c.getTime().getTime(); }
Example 26
From project android-api_1, under directory /android-lib/src/com/catchnotes/api/.
Source file: CatchAPI.java

private long parse3339(String time){ if (time == null || time.length() == 0) { return 0; } if (timestamper != null) { try { timestamper.parse3339(time); } catch ( TimeFormatException e) { log("caught a TimeFormatException parsing timestamp: \"" + time + '"',e); return 0; } return timestamper.normalize(false); } else { Date timestamp=new Date(); if (rfc3339 == null) { rfc3339=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); rfc3339.setTimeZone(TimeZone.getTimeZone("GMT+0")); rfc3339.setLenient(true); } try { timestamp=rfc3339.parse(time); } catch ( ParseException e) { log("caught a ParseException parsing timestamp: \"" + time + '"',e); return 0; } return timestamp.getTime(); } }
Example 27
From project android-rss, under directory /src/test/java/org/mcsoxford/rss/.
Source file: RSSParserTest.java

@Test public void parse() throws Exception { final RSSFeed feed=parse(stream); assertEquals("Example Channel",feed.getTitle()); assertEquals(Uri.parse("http://example.com/"),feed.getLink()); assertEquals("My example channel",feed.getDescription()); final Iterator<RSSItem> items=feed.getItems().iterator(); RSSItem item; item=items.next(); assertEquals("News for November",item.getTitle()); assertEquals(Uri.parse("http://example.com/2010/11/07"),item.getLink()); assertEquals("Other things happened today",item.getDescription()); assertTrue(item.getCategories().isEmpty()); GregorianCalendar calendar=new GregorianCalendar(2010,10,07,8,22,14); calendar.setTimeZone(TimeZone.getTimeZone("Etc/GMT")); Date expectedDate=calendar.getTime(); assertEquals(expectedDate,item.getPubDate()); assertEquals(2,item.getThumbnails().size()); MediaThumbnail expectedThumbnail0=new MediaThumbnail(Uri.parse("http://example.com/media/images/12/jpg/_7_2.jpg"),49,66); assertEquals(expectedThumbnail0.getUrl(),item.getThumbnails().get(0).getUrl()); assertEquals(expectedThumbnail0.getHeight(),item.getThumbnails().get(0).getHeight()); assertEquals(expectedThumbnail0.getWidth(),item.getThumbnails().get(0).getWidth()); MediaThumbnail expectedThumbnail1=new MediaThumbnail(Uri.parse("http://example.com/media/images/12/jpg/_7_2-1.jpg"),81,144); assertEquals(expectedThumbnail1.getUrl(),item.getThumbnails().get(1).getUrl()); assertEquals(expectedThumbnail1.getHeight(),item.getThumbnails().get(1).getHeight()); assertEquals(expectedThumbnail1.getWidth(),item.getThumbnails().get(1).getWidth()); item=items.next(); assertEquals("News for October",item.getTitle()); assertEquals(Uri.parse("http://example.com/2010/10/12"),item.getLink()); assertEquals("October days: we’re, <b>apple</b> ##<i>pie</i>",item.getDescription()); assertEquals("October days: we’re, <b>apple</b> ##<i>pie</i>",item.getContent()); assertEquals(2,item.getCategories().size()); assertTrue(item.getCategories().contains("Daily news")); assertTrue(item.getCategories().contains("October news")); assertEquals(0,item.getThumbnails().size()); assertFalse(items.hasNext()); }
Example 28
From project android-shuffle, under directory /client/src/org/dodgybits/shuffle/android/core/model/persistence/.
Source file: InitialDataGenerator.java

private Task createTask(String description,String details,int contextIndex,Project project,long start,long due){ Id contextId=contextIndex > -1 ? mPresetContexts[contextIndex].getLocalId() : Id.NONE; long created=System.currentTimeMillis(); String timezone=TimeZone.getDefault().getID(); Task.Builder builder=Task.newBuilder(); builder.setDescription(description).setDetails(details).setContextId(contextId).setProjectId(project == null ? Id.NONE : project.getLocalId()).setCreatedDate(created).setModifiedDate(created).setStartDate(start).setDueDate(due).setTimezone(timezone).setOrder(ORDER++); return builder.build(); }
Example 29
From project Android-SyncAdapter-JSON-Server-Example, under directory /src/com/example/android/samplesync/client/.
Source file: NetworkUtilities.java

/** * Fetches the list of friend data updates from the server * @param account The account being synced. * @param authtoken The authtoken stored in AccountManager for this account * @param lastUpdated The last time that sync was performed * @return list The list of updates received from the server. */ public static List<User> fetchFriendUpdates(Account account,String authtoken,Date lastUpdated) throws JSONException, ParseException, IOException, AuthenticationException { final ArrayList<User> friendList=new ArrayList<User>(); final ArrayList<NameValuePair> params=new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(PARAM_USERNAME,account.name)); params.add(new BasicNameValuePair(PARAM_PASSWORD,authtoken)); if (lastUpdated != null) { final SimpleDateFormat formatter=new SimpleDateFormat("yyyy/MM/dd HH:mm"); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); params.add(new BasicNameValuePair(PARAM_UPDATED,formatter.format(lastUpdated))); } Log.i(TAG,params.toString()); HttpEntity entity=null; entity=new UrlEncodedFormEntity(params); final HttpPost post=new HttpPost(FETCH_FRIEND_UPDATES_URI); post.addHeader(entity.getContentType()); post.setEntity(entity); maybeCreateHttpClient(); final HttpResponse resp=mHttpClient.execute(post); final String response=EntityUtils.toString(resp.getEntity()); if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { final JSONArray friends=new JSONArray(response); Log.d(TAG,response); for (int i=0; i < friends.length(); i++) { friendList.add(User.valueOf(friends.getJSONObject(i))); } } else { if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) { Log.e(TAG,"Authentication exception in fetching remote contacts"); throw new AuthenticationException(); } else { Log.e(TAG,"Server error in fetching remote contacts: " + resp.getStatusLine()); throw new IOException(); } } return friendList; }
Example 30
From project androidtracks, under directory /src/org/sfcta/cycletracks/.
Source file: SaveTrip.java

void activateSubmitButton(){ final Button btnSubmit=(Button)findViewById(R.id.ButtonSubmit); final Intent xi=new Intent(this,ShowMap.class); btnSubmit.setEnabled(true); btnSubmit.setOnClickListener(new View.OnClickListener(){ public void onClick( View v){ TripData trip=TripData.fetchTrip(SaveTrip.this,tripid); trip.populateDetails(); if (purpose.equals("")) { Toast.makeText(getBaseContext(),"You must select a trip purpose before submitting! Choose from the purposes above.",Toast.LENGTH_SHORT).show(); return; } EditText notes=(EditText)findViewById(R.id.NotesField); String fancyStartTime=DateFormat.getInstance().format(trip.startTime); SimpleDateFormat sdf=new SimpleDateFormat("m"); sdf.setTimeZone(TimeZone.getTimeZone("UTC")); String minutes=sdf.format(trip.endTime - trip.startTime); String fancyEndInfo=String.format("%1.1f miles, %s minutes. %s",(0.0006212f * trip.distance),minutes,notes.getEditableText().toString()); trip.updateTrip(purpose,fancyStartTime,fancyEndInfo,notes.getEditableText().toString()); trip.updateTripStatus(TripData.STATUS_COMPLETE); resetService(); InputMethodManager imm=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(),0); Intent i=new Intent(getApplicationContext(),MainInput.class); startActivity(i); xi.putExtra("showtrip",trip.tripid); xi.putExtra("uploadTrip",true); startActivity(xi); SaveTrip.this.finish(); } } ); }
Example 31
From project android_8, under directory /src/com/google/gson/.
Source file: DefaultTypeAdapters.java

DefaultDateTypeAdapter(DateFormat enUsFormat,DateFormat localFormat){ this.enUsFormat=enUsFormat; this.localFormat=localFormat; this.iso8601Format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'",Locale.US); this.iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); }
Example 32
From project android_packages_wallpapers_basic, under directory /src/com/android/wallpaper/fall/.
Source file: FallRS.java

@Override protected ScriptC createScript(){ mScript=new ScriptC_fall(mRS,mResources,R.raw.fall); createMesh(); createState(); createProgramVertex(); createProgramFragmentStore(); createProgramFragment(); loadTextures(); mScript.setTimeZone(TimeZone.getDefault().getID()); mScript.bind_g_Constants(mConstants); return mScript; }
Example 33
From project apb, under directory /modules/apb-base/src/apb/tasks/.
Source file: DownloadTask.java

private long getMDTM(@NotNull File file) throws IOException { URLConnection c=getConnection(); if ("FtpURLConnection".equals(c.getClass().getSimpleName())) { c.connect(); try { Object ftpClient=ClassUtils.fieldValue(c,"ftp"); ClassUtils.invokeNonPublic(ftpClient,"issueCommandCheck","MDTM " + file.getName()); String result=(String)ClassUtils.invoke(ftpClient,"getResponseString"); DateFormat df=new SimpleDateFormat("yyyyMMddHHmmss"); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df.parse(result.substring(4,result.length() - 1)).getTime(); } catch ( Exception e) { } } return 0; }
Example 34
From project AquaNotesTest, under directory /src/com/google/android/apps/iosched/ui/.
Source file: ScheduleFragment.java

private void setupDay(LayoutInflater inflater,long startMillis){ Day day=new Day(); day.index=mDays.size(); day.timeStart=startMillis; day.timeEnd=startMillis + DateUtils.DAY_IN_MILLIS; day.blocksUri=ScheduleContract.Blocks.buildBlocksBetweenDirUri(day.timeStart,day.timeEnd); 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); }
Example 35
From project archive-commons, under directory /archive-commons/src/main/java/org/archive/util/.
Source file: DateUtils.java

private static ThreadLocal<SimpleDateFormat> threadLocalDateFormat(final String pattern){ ThreadLocal<SimpleDateFormat> tl=new ThreadLocal<SimpleDateFormat>(){ protected SimpleDateFormat initialValue(){ SimpleDateFormat df=new SimpleDateFormat(pattern); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df; } } ; return tl; }
Example 36
From project azure4j-blog-samples, under directory /ACSManagementService/src/com/persistent/azure/acs/.
Source file: RelyingPartyCreator.java

/** * Assigns relying party key and addresses to the relying party. * @param relyingParty * @param name * @throws Exception */ private void assignRelyingPartyKeyAndAddresses(RelyingParty relyingParty,String name) throws Exception { RelyingPartyKey relyingPartyKey=new RelyingPartyKey(); relyingPartyKey.setDisplayName(name); relyingPartyKey.setType("X509Certificate"); relyingPartyKey.setUsage("Signing"); relyingPartyKey.setValue(getCertificateBytes(name)); relyingPartyKey.setRelyingPartyId(relyingParty.getId()); Calendar calendar=Calendar.getInstance(); SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.S z"); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); String startDate=dateFormat.format(calendar.getTime()); relyingPartyKey.setStartDate(dateFormat.parse(startDate)); calendar.add(Calendar.DAY_OF_YEAR,364); String endDate=dateFormat.format(calendar.getTime()); relyingPartyKey.setEndDate(dateFormat.parse(endDate)); relyingPartyKey.setPassword(certPassword.getBytes()); relyingPartyKey.setIsPrimary(true); managementService.addEntity(relyingPartyKey); assignRealm(relyingParty); assignReturnURL(relyingParty); }
Example 37
From project beintoo-android-sdk, under directory /BeintooSDK/src/com/beintoo/activities/marketplace/.
Source file: MarketplaceCoupon.java

private void loadData(){ try { String currencyName="Bedollars"; if (Beintoo.virtualCurrencyData != null) { currencyName=Beintoo.virtualCurrencyData.get("currencyName"); findViewById(R.id.buy_bedollar_logo).setVisibility(View.GONE); findViewById(R.id.buy_sendgift_bedollar_logo).setVisibility(View.GONE); } if ((Beintoo.virtualCurrencyData == null) && (MarketplaceList.userBedollars == null || MarketplaceList.userBedollars < price)) { ((ImageView)findViewById(R.id.buy_bedollar_logo)).setImageDrawable(mContext.getResources().getDrawable(R.drawable.b01)); ((ImageView)findViewById(R.id.buy_sendgift_bedollar_logo)).setImageDrawable(mContext.getResources().getDrawable(R.drawable.b01)); } Double price=(vgood.getVirtualCurrencyPrice() != null) ? vgood.getVirtualCurrencyPrice() : vgood.getBedollars(); ((TextView)findViewById(R.id.coupon_name)).setText(vgood.getName()); ((TextView)findViewById(R.id.coupon_name)).setSingleLine(true); ((TextView)findViewById(R.id.coupon_bedollars)).setText(mContext.getString(R.string.price) + price + " "+ currencyName); ((TextView)findViewById(R.id.coupon_bedollars_buy)).setText(price + " " + ((!currencyName.equals("Bedollars")) ? " " + currencyName : "")); ((TextView)findViewById(R.id.coupon_bedollars_sendgift)).setText(price + " " + ((!currencyName.equals("Bedollars")) ? " " + currencyName : "")); ((TextView)findViewById(R.id.coupon_title_large)).setText((vgood.getName().length() > 22) ? vgood.getName().substring(0,22) + "..." : vgood.getName()); ((TextView)findViewById(R.id.coupon_desc)).setText(vgood.getDescription()); SimpleDateFormat dateFormatter=new SimpleDateFormat("d-MMM-y HH:mm:ss",Locale.ENGLISH); dateFormatter.setTimeZone(TimeZone.getTimeZone("GMT")); Date msgDate=dateFormatter.parse(vgood.getEnddate()); dateFormatter.setTimeZone(TimeZone.getDefault()); ((TextView)findViewById(R.id.coupon_valid)).setText(mContext.getString(R.string.challEnd) + " " + DateFormat.getDateTimeInstance(DateFormat.MEDIUM,DateFormat.SHORT,Locale.getDefault()).format(msgDate)); ImageView img=(ImageView)findViewById(R.id.coupon_image); img.setTag(vgood.getImageUrl()); ImageManager imageDisplayer=new ImageManager(mContext); imageDisplayer.displayImage(vgood.getImageUrl(),mContext,img); imageDisplayer.interrupThread(); if (vgood.getRating() != null) ((RatingBar)findViewById(R.id.vgood_rating)).setRating(vgood.getRating()); } catch ( Exception e) { e.printStackTrace(); } }
Example 38
From project Birthdays, under directory /src/com/rexmenpara/birthdays/util/.
Source file: CalendarHelper.java

private String getCurrentTimeZoneString(){ String[] ids=TimeZone.getAvailableIDs(); for ( String id : ids) { if (TimeZone.getTimeZone(id).equals(TimeZone.getDefault())) { return id; } } return null; }
Example 39
From project BusFollower, under directory /src/net/argilo/busfollower/ocdata/.
Source file: RouteDirection.java

public Date getRequestProcessingTime(){ if (requestProcessingTime == null || requestProcessingTime.length() < 14) { return null; } try { int year=Integer.parseInt(requestProcessingTime.substring(0,4)); int month=Integer.parseInt(requestProcessingTime.substring(4,6)) - 1; int day=Integer.parseInt(requestProcessingTime.substring(6,8)); int hourOfDay=Integer.parseInt(requestProcessingTime.substring(8,10)); int minute=Integer.parseInt(requestProcessingTime.substring(10,12)); int second=Integer.parseInt(requestProcessingTime.substring(12,14)); Calendar calendar=Calendar.getInstance(TimeZone.getTimeZone("America/Toronto")); calendar.set(year,month,day,hourOfDay,minute,second); return calendar.getTime(); } catch ( NumberFormatException e) { Log.w(TAG,"Couldn't parse RequestProcessingTime: " + requestProcessingTime); return null; } }
Example 40
From project candlepin, under directory /src/test/java/org/candlepin/resource/util/.
Source file: ResourceDateParserTest.java

@Test public void parseDateTime(){ Date parsed=ResourceDateParser.parseDateString("1997-07-16T19:20:30-00:00"); Calendar cal=Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setTime(parsed); assertEquals(7,cal.get(Calendar.MONTH) + 1); assertEquals(16,cal.get(Calendar.DATE)); assertEquals(1997,cal.get(Calendar.YEAR)); assertEquals(7,cal.get(Calendar.HOUR)); assertEquals(20,cal.get(Calendar.MINUTE)); assertEquals(30,cal.get(Calendar.SECOND)); }
Example 41
From project cascading, under directory /src/core/cascading/operation/text/.
Source file: DateOperation.java

/** * Constructor DateOperation creates a new DateOperation instance. * @param numArgs of type int * @param fieldDeclaration of type Fields * @param dateFormatString of type String * @param zone of type TimeZone * @param locale of type Locale */ @ConstructorProperties({"numArgs","fieldDeclaration","dateFormatString","zone","locale"}) public DateOperation(int numArgs,Fields fieldDeclaration,String dateFormatString,TimeZone zone,Locale locale){ super(numArgs,fieldDeclaration); this.dateFormatString=dateFormatString; this.zone=zone; this.locale=locale; }
Example 42
From project chililog-server, under directory /src/main/java/org/chililog/server/engine/parsers/.
Source file: DateFieldParser.java

/** * Constructor * @param repoFieldInfo Field meta data * @throws ParseException */ public DateFieldParser(RepositoryFieldConfigBO repoFieldInfo) throws ParseException { super(repoFieldInfo); Hashtable<String,String> properties=repoFieldInfo.getProperties(); String defaultValue=properties.get(RepositoryFieldConfigBO.DEFAULT_VALUE_PROPERTY_NAME); _dateFormat=properties.get(RepositoryFieldConfigBO.DATE_FORMAT_PROPERTY_NAME); if (StringUtils.isBlank(_dateFormat)) { _dateFormat="yyyy-MM-dd'T'HH:mm:ssZ"; } SimpleDateFormat dateFormatter=new SimpleDateFormat(_dateFormat); String t=properties.get(RepositoryFieldConfigBO.DATE_TIMEZONE_PROPERTY_NAME); if (!StringUtils.isBlank(t)) { _dateTimezone=TimeZone.getTimeZone(t); dateFormatter.setTimeZone(_dateTimezone); } if (!StringUtils.isBlank(defaultValue)) { _defaultValue=dateFormatter.parse(defaultValue); } }
Example 43
From project CHMI, under directory /src/org/kaldax/app/chmi/img/.
Source file: LighningImagesHandler.java

public String getImageName(Date date){ Calendar cal=Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.setTime(date); String strResult="pacz21.blesk."; int iYear=cal.get(Calendar.YEAR); strResult=strResult + new Integer(iYear).toString(); int iMonth=cal.get(Calendar.MONTH) + 1; if (iMonth < 10) { strResult=strResult + "0"; } strResult=strResult + new Integer(iMonth).toString(); int iDay=cal.get(Calendar.DATE); if (iDay < 10) { strResult=strResult + "0"; } strResult=strResult + new Integer(iDay).toString(); strResult=strResult + "."; int iHour=cal.get(Calendar.HOUR_OF_DAY); if (iHour < 10) { strResult=strResult + "0"; } strResult=strResult + new Integer(iHour).toString(); int iMinutes=cal.get(Calendar.MINUTE); if (iMinutes < 10) { strResult=strResult + "0"; } strResult=strResult + new Integer(iMinutes).toString(); strResult=strResult + ".10_9"; return strResult; }
Example 44
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/hicc/.
Source file: OfflineTimeHandler.java

public OfflineTimeHandler(HashMap<String,String> map,String tz){ if (tz != null) { this.tz=TimeZone.getTimeZone(tz); } else { this.tz=TimeZone.getTimeZone("UTC"); } init(map); }
Example 45
From project clearcase-plugin, under directory /src/main/java/hudson/plugins/clearcase/action/.
Source file: UcmDynamicCheckoutAction.java

public boolean checkoutCodeFreeze(String viewName) throws IOException, InterruptedException { synchronized (build.getProject()) { ClearCaseDataAction clearcaseDataAction=null; Run previousBuild=build.getPreviousBuild(); while (previousBuild != null) { clearcaseDataAction=previousBuild.getAction(ClearCaseDataAction.class); if (previousBuild.isBuilding() && clearcaseDataAction != null && clearcaseDataAction.getStream().equals(stream)) throw new IOException("Can't run build on stream " + stream + " when build "+ previousBuild.getNumber()+ " is currently running on the same stream."); previousBuild=previousBuild.getPreviousBuild(); } } prepareBuildStreamAndViews(viewName,stream); SimpleDateFormat formatter=new SimpleDateFormat("d-MMM-yy_HH_mm_ss",Locale.US); formatter.setTimeZone(TimeZone.getTimeZone("UTC")); String dateStr=formatter.format(build.getTimestamp().getTime()).toLowerCase(); getCleartool().mkbl((BASELINE_NAME + dateStr),getConfiguredStreamViewName(),(BASELINE_COMMENT + dateStr),false,false,null,null,null); List<Baseline> latestBlsOnConfgiuredStream=UcmCommon.getLatestBlsWithCompOnStream(getCleartool(),stream,getConfiguredStreamViewName()); for ( Baseline baseLineDesc : latestBlsOnConfgiuredStream) { if (baseLineDesc.isNotLabeled() && baseLineDesc.getComponentDesc().isModifiable()) { List<String> readWriteCompList=new ArrayList<String>(); readWriteCompList.add(baseLineDesc.getComponentDesc().getName()); List<Baseline> baseLineDescList=getCleartool().mkbl((BASELINE_NAME + dateStr),getConfiguredStreamViewName(),(BASELINE_COMMENT + dateStr),false,true,readWriteCompList,null,null); String newBaseline=baseLineDescList.get(0).getBaselineName() + "@" + UcmCommon.getVob(baseLineDesc.getComponentDesc().getName()); baseLineDesc.setBaselineName(newBaseline); } } UcmCommon.rebase(getCleartool(),viewName,latestBlsOnConfgiuredStream); ClearCaseDataAction dataAction=build.getAction(ClearCaseDataAction.class); if (dataAction != null) dataAction.setLatestBlsOnConfiguredStream(latestBlsOnConfgiuredStream); return true; }
Example 46
From project collections-generic, under directory /src/test/org/apache/commons/collections15/.
Source file: TestFactoryUtils.java

public void testInstantiateFactoryComplex(){ TimeZone.setDefault(TimeZone.getTimeZone("GMT")); Factory factory=FactoryUtils.instantiateFactory(Date.class,new Class[]{Integer.TYPE,Integer.TYPE,Integer.TYPE},new Object[]{new Integer(70),new Integer(0),new Integer(2)}); assertNotNull(factory); Object created=factory.create(); assertTrue(created instanceof Date); assertEquals(new Date(1000 * 60 * 60* 24),created); }
Example 47
From project commons-compress, under directory /src/test/java/org/apache/commons/compress/archivers/tar/.
Source file: TarArchiveInputStreamTest.java

private void datePriorToEpoch(String archive) throws Exception { URL tar=getClass().getResource(archive); TarArchiveInputStream in=null; try { in=new TarArchiveInputStream(new FileInputStream(new File(new URI(tar.toString())))); TarArchiveEntry tae=in.getNextTarEntry(); assertEquals("foo",tae.getName()); Calendar cal=Calendar.getInstance(TimeZone.getTimeZone("GMT")); cal.set(1969,11,31,23,59,59); cal.set(Calendar.MILLISECOND,0); assertEquals(cal.getTime(),tae.getLastModifiedDate()); assertTrue(tae.isCheckSumOK()); } finally { if (in != null) { in.close(); } } }
Example 48
From project conference-mobile-app, under directory /android-app/src/com/google/android/apps/iosched/ui/.
Source file: ScheduleFragment.java

private void setupDay(LayoutInflater inflater,long startMillis){ Day day=new Day(); day.index=mDays.size(); day.timeStart=startMillis; day.timeEnd=startMillis + DateUtils.DAY_IN_MILLIS; day.blocksUri=ScheduleContract.Blocks.buildBlocksBetweenDirUri(day.timeStart,day.timeEnd); 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); }
Example 49
From project db2triples, under directory /src/main/java/net/antidot/sql/model/core/.
Source file: SQLConnector.java

/** * Get time zone stored in MySQL database. Reference : http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html The result can be NULL if the Timezone can't be determinated. The appropriated timezone returned follow these priorities : 1) If * @param conn * @return * @throws SQLException */ public static String getTimeZone(Connection conn) throws SQLException { if (log.isDebugEnabled()) log.debug("[SQLConnector:getTimeZone]"); Statement stmt=conn.createStatement(); String query="SELECT @@global.time_zone, @@session.time_zone;"; ResultSet rs=stmt.executeQuery(query); while (rs.next()) { String globalMySQLTimeZone=rs.getString("@@global.time_zone"); String sessionMySQLTimeZone=rs.getString("@@session.time_zone"); String mySQLTimeZone=globalMySQLTimeZone; if (!globalMySQLTimeZone.equals(sessionMySQLTimeZone)) { mySQLTimeZone=sessionMySQLTimeZone; } if (log.isDebugEnabled()) log.debug("[SQLConnector:getTimeZone] mySQLTimeZone extracted = " + mySQLTimeZone); return getTimeZoneFromMySQLFormat(mySQLTimeZone); } if (log.isWarnEnabled()) log.warn("[SQLConnector:getTimeZone] Impossible to read timezone from database. Timezone of current system selected."); return timeZoneToStr(TimeZone.getTimeZone("UTC")); }