Java Code Examples for java.util.Date

The following are top voted examples for showing how to use java.util.Date. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: jentrata-msh   File: SchedulerTask.java View source code 9 votes vote down vote up
/**
 * Check whether housecleaning should perform or not.
 * 
 * @param time
 * @return
 * @throws ParseException
 */
private boolean checkStartTime(String time) throws Exception {
	Date cur = new Date();
	try {
		Date run = getDateFormat().parse(time);
		return cur.after(run);
	} catch (ParseException e) {
		AdminError("Parse error when checking the start time.");
		throw new Exception("Parse error when checking the start time.", e);
	}

}
 
Example 2
Project: my-ministry-assistant   File: TimeUtils.java View source code 6 votes vote down vote up
public static long timestampToMillis(String timestamp, long defaultValue) {
    if (TextUtils.isEmpty(timestamp)) {
        return defaultValue;
    }
    Date d = parseTimestamp(timestamp);
    return d == null ? defaultValue : d.getTime();
}
 
Example 3
Project: netlib   File: TorX509TrustManager.java View source code 6 votes vote down vote up
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
    if (chain.length != 2) {
        throw new CertificateException("Certificate Chain length != 2");
    }
        
    String dnName0 = chain[0].getSubjectDN().getName();
    String dnName1 = chain[1].getSubjectDN().getName();

    Matcher dnName0Match = cnPattern.matcher(dnName0);
    Matcher dnName1Match = cnPattern.matcher(dnName1);

    if (!dnName0Match.matches() || !dnName1Match.matches()) {
        log.warning("TorX509TrustManager.checkServerTrusted(): not matched"+
                " dnName0="+dnName0+", dnName1="+dnName1);
        throw new CertificateException("Name field of Certificate does not have the right format");
    }

    dnName0 = dnName0Match.group(1);
    dnName1 = dnName1Match.group(1);
            
    if (dnName1.indexOf(dnName0) > 1) {
        throw new CertificateException("Certifier and Certificate owner don't have the same name");
    }
    
    // XXX: It seems that the string has changed to <signing>, though 
    // the second chapter of main-tor-spec still says <identity>
    log.finer("dnName0 = "+dnName0.toString()+", dnName1 = "+dnName1.toString());   
    if (dnName1.indexOf("<identity>") != -1 && dnName1.indexOf("<signing>") != -1) {
        throw new CertificateException("Certifier Field does not have the required form");
    }

    Date now = new Date();
    if (now.before(chain[0].getNotBefore())) {
        throw new CertificateException("Certificate is not valid yet");
    }
    if (now.after(chain[0].getNotAfter())) {
        throw new CertificateException("Certificate has expired");
    }
    
    // TODO: the subject unique ID has to be extracted from the ASN1
    // stuff of the Directory entry and compared to the one given here.
}
 
Example 4
Project: kinballwc2015   File: Match.java View source code 6 votes vote down vote up
@Override
public int compare(Match match1, Match match2) {
    Date date1;
    Date date2;
    if (match1.getDateToShow() == null) {
        date1 = match1.getDate();
    } else {
        date1 = match1.getDateToShow();
    }
    if (match2.getDateToShow() == null) {
        date2 = match2.getDate();
    } else {
        date2 = match2.getDateToShow();
    }

    int result = date1.compareTo(date2);
    if (result == 0) {
        result = match1.getCourt() - match2.getCourt();
        if (result == 0) {
            result = match1.getTitle().compareTo(match2.getTitle());
        }
    }
    return result;
}
 
Example 5
Project: UnicentaPOS_AD   File: JTimePanel.java View source code 6 votes vote down vote up
public void setDate(Date dNewDate) {        
     
    Date dOldDate = m_jclock.getTime();
    if (((dNewDate == null && dOldDate != null) || (dNewDate != null && !dNewDate.equals(dOldDate)))
        && checkDates(dNewDate)) {             
            m_jclock.setTime(dNewDate);
            renderTime();                
            firePropertyChange("Date", dOldDate, dNewDate); // decimos al mundo que ha cambiado la propiedad fecha
    }
}
 
Example 6
Project: jentrata-msh   File: EbmsUtilityTest.java View source code 6 votes vote down vote up
/**
 * Test for converting from GMT datetime representation to java date object.  
 */
public void testGMT2Date_Pos0() throws Exception {
	
	Date date 	 = new Date();		
	
	String dateTime = date.toString();
	
	Date convertedDate = EbmsUtility.GMT2Date(dateTime);
	
	System.out.println("GMT converted: " + convertedDate);
	
	// Since the millisecond pecision will be lost during conversion.
	// we need to create a calendar and set the millisecond to zero. 
	Calendar cal = Calendar.getInstance();		
	cal.setTimeInMillis(date.getTime());
	cal.set(Calendar.MILLISECOND, 0);
	
	// Check whether the time is equal or not. 
	TestCase.assertEquals(convertedDate.getTime(), cal.getTimeInMillis());
}
 
Example 7
Project: UnicentaPOS_AD   File: LeavesView.java View source code 6 votes vote down vote up
private boolean IsValidEndDate(Date date) {
    Date systemDate = new Date();
    if (! m_jStartDate.getText().equals("")) {
        Date startdate;
        try {
            startdate = (Date) Formats.TIMESTAMP.parseValue(m_jStartDate.getText());
            return (startdate.before(date) 
                    || (startdate.getDate() == date.getDate() 
                    && startdate.getMonth() == date.getMonth() 
                    && startdate.getYear() == date.getYear()));
            
        } catch (BasicException ex) {
        }
    }
    return (systemDate.before(date) 
            || (systemDate.getDate() == date.getDate() 
            && systemDate.getMonth() == date.getMonth() 
            && systemDate.getYear() == date.getYear()));
}
 
Example 8
Project: aipo   File: ALDateContainer.java View source code 6 votes vote down vote up
/**
 * ???????????
 * 
 * @param date
 */
public void setDate(Date date) {
  if (date != null) {
    this.date = (Date) date.clone();
  }

  try {
    Calendar calendar = new GregorianCalendar();
    if (date == null) {
      year = null;
      month = null;
      day = null;
    } else {
      calendar.setTime(date);
      year = Integer.toString(calendar.get(Calendar.YEAR));
      month = Integer.toString(calendar.get(Calendar.MONTH) + 1);
      day = Integer.toString(calendar.get(Calendar.DATE));
    }
  } catch (Throwable ex) {
    year = null;
    month = null;
    day = null;
  }
}
 
Example 9
Project: arduino-android   File: HeatingMonitor.java View source code 6 votes vote down vote up
private void handleTimeSlot(String key) 
{
	Date d = new Date();
	String temp;
	int day = d.getDay();
	Log.d("SRM", "d="+day);
	if (day > 0 && day < 6)
	{
	    Log.d("SRM", "weekday");
		temp = getSetting("TEMP_d" + key);
	}
	else
	{
	    Log.d("SRM", "weekend");
		temp = getSetting("TEMP_w" + key);
	}
	String hourFromS = key.substring(0,2);
	String hourToS = key.substring(2,4);
	int hourFrom = Integer.parseInt(hourFromS);
	int hourTo = Integer.parseInt(hourToS);
	int hour = d.getHours();
	if (hour >= hourFrom && hour < hourTo)
	{
		DigitalOutputs outputs = mActivity.outputs;
		int t = Integer.parseInt(temp);
		if ("C".equals(getSetting("UNITS")))
		{
			t = (t * 9) / 5 + 32;
		}
		t = t + 20; // fiddle factor  deg F - sensor gets warm in box
		outputs.setOutput(0x41, t);
	}
}
 
Example 10
Project: tuberun_android   File: PlanFetcher.java View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
private Route getRouteFromNode(Node route) {
	Route result = new Route();
	NamedNodeMap attributes = route.getAttributes();

	Node duration = attributes.getNamedItem("publicDuration");
	String dur = duration.getNodeValue();
	String[] tokens = dur.split(":");
	Date ddur = new Date();
	ddur.setHours(Integer.parseInt(tokens[0]));
	ddur.setMinutes(Integer.parseInt(tokens[1]));
	result.setDuration(ddur);

	Node name = attributes.getNamedItem("changes");
	result.setChanges(Integer.parseInt(name.getNodeValue()));

	Node distance = attributes.getNamedItem("distance");
	result.setDistance(Integer.parseInt(distance.getNodeValue()));

	NodeList children = route.getChildNodes();
	for (int i = 0; i < children.getLength(); i++) {
		Node c = children.item(i);
		if (!c.getNodeName().equals("itdPartialRouteList"))
			continue;
		NodeList partials = c.getChildNodes();
		for (int j = 0; j < partials.getLength(); j++) {
			result.addPartialRoute(getPartialRouteFromNode(partials.item(j)));
		}
		break;
	}

	return result;
}
 
Example 11
Project: arduino-android   File: TimerMonitor.java View source code 6 votes vote down vote up
private void handleTimerNumber(int i) 
{
	String itemStr = getSetting("TIMER_OP" + i);
	if ("null".equals(itemStr))
	{
		return; // timer not in use
	}
	String startTimeStr = getSetting("TIMER_ON"+ i);
	String endTimeStr = getSetting("TIMER_OFF" + i);
	int start = Integer.parseInt(startTimeStr);
	int end = Integer.parseInt(endTimeStr);
	int op = Integer.parseInt(itemStr);
	// compare with time now and if it should be on, but isn't, turn it on.
	// the times can just be compared as 4 digit numbers
	Date d = new Date();
	int t = d.getHours() * 100 + d.getMinutes();

	boolean shouldBeOn = false;
	// if the off time appears to be before the on time, then it refers to the next day
	if (end < start)
	{
		end = end + 2400;
	}
	shouldBeOn = (t >= start && t < end);
	DigitalOutputs outputs = mActivity.outputs;
	if (shouldBeOn && ! outputs.isOn(op))
	{
		outputs.turnOn(op);
	}
	if (! shouldBeOn && outputs.isOn(op))
	{
		outputs.turnOff(op);
	}
}
 
Example 12
Project: tdq-studio-se   File: DateChanger.java View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
Date modifyDateValue(Date date) {
    if (date == null) {
        return null;
    }

    int choice = random.nextInt(3);
    switch (choice) {
    case 0:
        date.setYear(random.nextInt(200));
        break;
    case 1:
        date.setMonth(random.nextInt(12));
        break;
    case 2:
        date.setDate(random.nextInt(31) + 1);
        break;
    default:
        break;
    }
    return date;
}
 
Example 13
Project: dashbuilder   File: TimeFrameTest.java View source code 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    Date startTime = new Date();
    startTime.setYear(115);
    startTime.setMonth(10);
    startTime.setDate(10);
    startTime.setHours(12);
    startTime.setMinutes(50);
    startTime.setSeconds(30);
    TimeInstant.START_TIME = startTime;

}
 
Example 14
Project: dashbuilder   File: IntervalListSecond.java View source code 6 votes vote down vote up
public Interval locateInterval(Object value) {
    Date d = (Date) value;
    int sec = d.getSeconds();
    if (sec > 59) {
        return intervalMap.get(59);
    } else {
        return intervalMap.get(sec);
    }
}
 
Example 15
Project: levelup-java-examples   File: XMLToArrayListXstream.java View source code 6 votes vote down vote up
@Before
public void setUp() {

	Funeral funeral1 = new Funeral(Date.from(Instant.now()),
			"Nitardy Funeral Home", "Jack");
	Funeral funeral2 = new Funeral(Date.from(Instant.now()),
			"Dunlap Memorial Home", "Cindie");
	Funeral funeral3 = new Funeral(Date.from(Instant.now()),
			"Olsen Funeral Home", "Perry");

	funerals = Lists.newArrayList(funeral1, funeral2, funeral3);
}
 
Example 16
Project: dk   File: RechargeService.java View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
public static String getNeedTime(Date currDate) {
	try {
		String currDateStr = DateUtil.YYYY_MM_DD.format(currDate);
		currDate = DateUtil.YYYY_MM_DD.parse(currDateStr);
		long currTime = Date.parse(currDate.toString());
		long delTime = IConstants.WITHDRAW_TIME * 24 * 60 * 60 * 1000;
		long needTime = currTime - delTime;
		Date needDate = new Date();
		needDate.setTime(needTime);
		String needDateStr = DateUtil.YYYY_MM_DD.format(needDate);
		return needDateStr;
	} catch (Exception ex) {
		ex.printStackTrace();
		return null;
	}
}
 
Example 17
Project: siarhei.luskanau.gps.tracker.free   File: DateDubugInfo.java View source code 6 votes vote down vote up
public static DateDubugInfo createDateDubugInfo() {
    try {
        DateDubugInfo dateDubugInfo = new DateDubugInfo();
        Date date = new Date();
        dateDubugInfo.formattedTime = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss", Locale.ENGLISH)
                .format(date);
        dateDubugInfo.timezoneOffset = date.getTimezoneOffset();
        dateDubugInfo.millisecond = date.getTime();
        return dateDubugInfo;
    } catch (Throwable t) {
    }
    return null;
}
 
Example 18
Project: dk   File: FrontMyPaymentAction.java View source code 6 votes vote down vote up
@SuppressWarnings("deprecation")
public static String changeEndTime(String endTime) {
	if (endTime != null && !endTime.equals("")) {
		String[] strs = endTime.split("-");
		// ?????????,????0??????????
		Date date = new Date();// ???
		long time = Date.UTC(Convert.strToInt(strs[0], -1) - 1900, Convert.strToInt(strs[1], -1) - 1, Convert.strToInt(strs[2], -1), 0, 0, 0);
		date.setTime(time);
		Calendar calendar = new GregorianCalendar();
		calendar.setTime(date);
		calendar.add(Calendar.DATE, 1);// ?????????.?????,??????
		date = calendar.getTime();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		return formatter.format(date);
	}
	return null;
}
 
Example 19
Project: SecurePhoto   File: TimeUpdateTask.java View source code 6 votes vote down vote up
@Override
public void run() {
    Calendar c = Calendar.getInstance();
    Date time = c.getTime();
    final String timeString = time.toLocaleString();

    activity.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            TextView cameraDate = (TextView) activity.findViewById(R.id.camera_date);
            if (cameraDate != null)
                cameraDate.setText(timeString);
        }
    });
}
 
Example 20
Project: google-web-toolkit-svnmirror   File: DateTest.java View source code 6 votes vote down vote up
/** Testing for public java.lang.String java.util.Date.toGMTString(). */
public void testToGMTString() {

  // We can't rely on the JRE's toString, as it is an implementation detail.
  if (GWT.isScript()) {
    // /////////////////////////////
    // Past
    // /////////////////////////////
    Date accum1 = create(PAST);
    String a1 = accum1.toGMTString();
    assertEquals("5 Jan 1880 00:00:00 GMT", a1);

    // /////////////////////////////
    // Future
    // /////////////////////////////
    Date accum2 = create(FUTURE);
    String a2 = accum2.toGMTString();
    assertEquals("30 Dec 2030 03:04:05 GMT", a2);
  }
}
 
Example 21
Project: milton2   File: DefaultETagGenerator.java View source code 6 votes vote down vote up
@Override
 public String generateEtag( Resource r ) {
     log.trace( "generateEtag" );
     if ( r == null ) {
     	return null;
     }
     String s = r.getUniqueId();
     if( s == null ) {
if( log.isTraceEnabled()) {
	log.trace("no uniqueId, so no etag for class: {}", r.getClass());
}
         return null;
     } else {
         Date dt = r.getModifiedDate();
         if( dt != null ) {
             log.trace("combine uniqueId with modDate to make etag");
             s = s + "_" + dt.hashCode();
         } else {
             log.trace("no modDate, so etag is just unique id");
         }
         return "\"" + s + "\"";
     }
 }
 
Example 22
Project: jentrata-msh   File: ClusterAudit.java View source code 5 votes vote down vote up
/**
    * The method is invoked constantly with interval defined in the configuration
    * descriptor or 60 second by default.
    * 
    * @return true if this method should be invoked again after a defined interval.
    */
   public boolean execute() {
// Lazy initialization. 
if (!this.initialized)
    this.initialize();

int counter = 0;

try {
    long timeStamp = getHostTimestamp(Hostname);
    String oldHostname = "";
    Date date = new Date();
    long currentTimestamp = date.getTime();
    
    // Check if audit starttime is passed or not
    if (timeStamp > currentTimestamp) {
	date.setTime( timeStamp );
	EbmsProcessor.core.log.debug ( "ClusterAudit: wait (" + date.toString() + ")");
    } else {
	EbmsProcessor.core.log.debug ( "ClusterAudit: start (" + date.toString() + ")");
	// To prevent more hosts auditing the cluster at the same time the
	// status of our host is set to auditor. Then the cluster is checked
	// if this is the only auditor in the cluster. In case this is the
	// only auditor the audit will start. In case it is not the only
	// auditor the audit will be skipped and this host will be added
	// at the end of the cluster list.
	updateStatusHostname( Hostname, "auditor" );
	if (uniqueAuditor(Hostname)) {
	    // Walk through the list of hosts inside this cluster
	    List clusterDVOList = clusterDAO.findClusterAllEntries();
	    Iterator i = clusterDVOList.iterator();
	    while (i.hasNext()) {
		ClusterDVO clusterEntry = (ClusterDVO) i.next();
		oldHostname = clusterEntry.getHostname();
		EbmsProcessor.core.log.debug ( "ClusterAudit: check host: " + oldHostname );
		counter = 0;
		// Skip this host and check if the host is available
		if (!oldHostname.equals(Hostname) && !hostIsAvailable(oldHostname)) {
		    EbmsProcessor.core.log.debug ( "ClusterAudit: host no longer available: " + oldHostname );
		    // Replace hostname for those messages that are still related to the other host
		    counter = replaceHostname( Hostname, oldHostname );
		    if (counter == 0) {
			// If there are no messages left in the other host remove it from the cluster list
			EbmsProcessor.core.log.debug ( "ClusterAudit: remove host: " + oldHostname );
			removeHostname( oldHostname );
		    } else {
			// Update the status of the host to inactive
			EbmsProcessor.core.log.debug ( "ClusterAudit: inactive host: " + oldHostname + " message(s) moved" );
			updateStatusHostname( oldHostname, "inactive" );
		    }
		}
	    }
	}
	// Put us at the end of the cluster list
	registerCurrentHost();
	EbmsProcessor.core.log.debug ( "ClusterAudit: end (" + date.toString() + ")");
    }
}catch(DAOException daoe){
    EbmsProcessor.core.log.fatal("ClusterAudit: Unable to complete cluster audit." + daoe);
}
return true;
   }