Java Code Examples for java.util.Date

The following examples show how to use java.util.Date. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: HIS   Source File: BmsInvoiceServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int reprintInvoice(Long newInvoiceNo, Long oldInvoiceNo) {
    BmsInvoiceRecordExample bmsInvoiceRecordExample = new BmsInvoiceRecordExample();
    bmsInvoiceRecordExample.createCriteria().andInvoiceNoEqualTo(oldInvoiceNo);
    List<BmsInvoiceRecord> bmsInvoiceRecordList = bmsInvoiceRecordMapper.selectByExample(bmsInvoiceRecordExample);
    if (!bmsInvoiceRecordList.isEmpty()){
        BmsInvoiceRecord bmsInvoiceRecord = bmsInvoiceRecordList.get(0);
        BmsInvoiceRecord newBmsInvoiceRecord = new BmsInvoiceRecord();
        BeanUtils.copyProperties(bmsInvoiceRecord,newBmsInvoiceRecord);
        bmsInvoiceRecord.setType(4);
        newBmsInvoiceRecord.setInvoiceNo(newInvoiceNo);
        newBmsInvoiceRecord.setType(1);
        newBmsInvoiceRecord.setCreateTime(new Date());
        bmsInvoiceRecordMapper.updateByPrimaryKeySelective(bmsInvoiceRecord);
        bmsInvoiceRecordMapper.insertSelective(newBmsInvoiceRecord);
        return 1;
    }
    return 0;
}
 
Example 2
@Test
public void testGetIntervalWithStartDate() {

  given()
    .queryParam("startDate", DATE_FORMAT_WITH_TIMEZONE.format(new Date(0)))
    .then()
      .expect()
        .statusCode(Status.OK.getStatusCode())
    .when()
      .get(METRICS_URL);

  verify(meterQueryMock).name(null);
  verify(meterQueryMock).reporter(null);
  verify(meterQueryMock).startDate(new Date(0));
  verify(meterQueryMock, times(1)).interval();
  verifyNoMoreInteractions(meterQueryMock);
}
 
Example 3
@BeforeEach
public void init() throws Exception {
	documentToSign = new InMemoryDocument("Hello World".getBytes());

	signatureParameters = new CAdESSignatureParameters();
	signatureParameters.bLevel().setSigningDate(new Date());
	signatureParameters.setSigningCertificate(getSigningCert());
	signatureParameters.setCertificateChain(getCertificateChain());
	signatureParameters.setSignaturePackaging(SignaturePackaging.ENVELOPING);
	signatureParameters.setSignatureLevel(SignatureLevel.CAdES_BASELINE_T);
	CAdESTimestampParameters signatureTimestampParameters = new CAdESTimestampParameters(DigestAlgorithm.SHA1);
	signatureParameters.setSignatureTimestampParameters(signatureTimestampParameters);

	service = new CAdESService(getOfflineCertificateVerifier());
	service.setTspSource(getGoodTsa());
}
 
Example 4
private String getOnDutyTime(List<AttendanceDetailMobile> mobileDetails) throws Exception {
	Date onDutyTime = null;
	Date signTime = null;
	String onDutyTimeString = null;
	for( AttendanceDetailMobile detailMobile : mobileDetails ) {
		signTime = dateOperation.getDateFromString(detailMobile.getSignTime() );
		if( onDutyTime != null && signTime != null && onDutyTime.after( signTime )) {
			onDutyTime = signTime;
			onDutyTimeString = detailMobile.getSignTime();
		}else if( onDutyTime == null ){
			onDutyTime = signTime;
			onDutyTimeString = detailMobile.getSignTime();
		}
	}
	return onDutyTimeString;
}
 
Example 5
Source Project: lams   Source File: NoticeboardContent.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** full constructor */
   public NoticeboardContent(Long nbContentId, String title, String content, boolean defineLater,
    boolean reflectOnActivity, String reflectInstructions, boolean contentInUse, Long creatorUserId,
    Date dateCreated, Date dateUpdated, boolean allowComments, boolean commentsLikeAndDislike,
    boolean allowAnonymous) {
this.nbContentId = nbContentId;
this.title = title;
this.content = content;
this.defineLater = defineLater;
this.reflectOnActivity = reflectOnActivity;
this.reflectInstructions = reflectInstructions;
this.contentInUse = contentInUse;
this.creatorUserId = creatorUserId;
this.dateCreated = dateCreated;
this.dateUpdated = dateUpdated;
this.allowComments = allowComments;
this.commentsLikeAndDislike = commentsLikeAndDislike;
this.allowAnonymous = allowAnonymous;
this.nbSessions = new HashSet<NoticeboardSession>();
   }
 
Example 6
Source Project: elephant   Source File: MessageRequestProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private MessageEntity buildMessageEntity(byte[] body,SendMessageRequestHeader requestHeader,boolean isTransaction) {
	MessageEntity entity = new MessageEntity();
	entity.setBody(body);
	entity.setCreateTime(new Date());
	entity.setDestination(requestHeader.getDestination());
	entity.setGroup(requestHeader.getProducerGroup());
	entity.setMessageId(requestHeader.getMessageId());
	entity.setProperties(requestHeader.getProperties());
	entity.setSendStatus(SendStatus.WAIT_SEND.getStatus());
	entity.setUpdateTime(entity.getCreateTime());
	
	if(isTransaction) {
		entity.setTransaction(true);
		entity.setStatus(MessageStatus.CONFIRMING.getStatus());
	}else {
		entity.setTransaction(false);
		entity.setStatus(MessageStatus.CONFIRMED.getStatus());
	}
	return entity;
}
 
Example 7
public ProfilingWriter(BlockingQueue<ProfilingEntry> jobQueue) {
    this.jobQueue = jobQueue;
    serverDto = ConfigReader.getCollectorServer();
    runningSince = new Date();

    final MongoDbAccessor mongo = getMongoDbAccessor();
    try {
        final MongoCollection<Document> profileCollection = getProfileCollection(mongo);

        IndexOptions indexOptions = new IndexOptions();
        indexOptions.background(true);
        LOG.info("Create index {ts:-1, lbl:1} in the background if it does not yet exists");
        profileCollection.createIndex(new BasicDBObject("ts",-1).append("lbl", 1), indexOptions);
        LOG.info("Create index {adr:1, db:1, ts:-1} in the background if it does not yet exists");
        profileCollection.createIndex(new BasicDBObject("adr",1).append("db",1).append("ts", -1), indexOptions);

        LOG.info("ProfilingWriter is ready at {}", serverDto.getHosts());

    } catch (MongoException e) {
        LOG.error("Exception while connecting to: {}", serverDto.getHosts(), e);
    }
}
 
Example 8
@Override
public CalendarEventEdit generateEvent(SignupMeeting m, SignupTimeslot ts) {
	
	//only interested in first site
	String siteId = m.getSignupSites().get(0).getSiteId();
	
	Date start;
	Date end;
	//use timeslot if set, otherwise use meeting
	if(ts == null) {
		start = m.getStartTime();
		end = m.getEndTime();
	} else {
		start = ts.getStartTime();
		end = ts.getEndTime();
	}
	String title = m.getTitle();
	String description = m.getDescription();
	String location = m.getLocation();
	
	//note that there is no way to set the creator unless the user creating the event is the current session user
	//and sometimes this is not the case, esp for transient events that are not persisted
		
	return generateEvent(siteId,start,end,title,description,location);
}
 
Example 9
@Test(dataProvider = "TransportType")
public void doTest(CougarClientWrapper.TransportType tt) throws Exception {
    // Set up the client to use rescript transport
    CougarClientWrapper cougarClientWrapper1 = CougarClientWrapper.getInstance(tt);
    CougarClientWrapper wrapper = cougarClientWrapper1;
    BaselineSyncClient client = cougarClientWrapper1.getClient();
    ExecutionContext context = cougarClientWrapper1.getCtx();
    // Create a date object to be passed as a parameter
    CougarClientResponseTypeUtils cougarClientResponseTypeUtils2 = new CougarClientResponseTypeUtils();
    CougarHelpers helper = new CougarHelpers();
   Date convertedDate= helper.convertToSystemTimeZone("2009-06-01T13:50:00.0Z");
    Date dateParam = cougarClientResponseTypeUtils2.createDateFromString("2009-06-01T13:50:00.0Z");
    // Make call to the method via client and validate the response is as expected
    SimpleResponse response3 = client.testParameterStylesQA(context, com.betfair.baseline.v2.enumerations.TestParameterStylesQAHeaderParamEnum.Foo, "this & that is 100%", convertedDate);
    assertEquals("headerParam=Foo,queryParam=this & that is 100%,dateQueryParam="+helper.dateInUTC(convertedDate), response3.getMessage());
}
 
Example 10
Source Project: ant-ivy   Source File: FileSystemResolverTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testFormattedLatestRevision() throws Exception {
    FileSystemResolver resolver = new FileSystemResolver();
    resolver.setName("test");
    resolver.setSettings(settings);
    assertEquals("test", resolver.getName());

    resolver.addIvyPattern(IVY_PATTERN);
    resolver.addArtifactPattern(settings.getBaseDir() + "/test/repositories/1/"
            + "[organisation]/[module]/[type]s/[artifact]-[revision].[type]");

    resolver.setLatestStrategy(new LatestRevisionStrategy());

    ModuleRevisionId mrid = ModuleRevisionId.newInstance("org1", "mod1.1", "1.1");
    ResolvedModuleRevision rmr = resolver.getDependency(new DefaultDependencyDescriptor(
            ModuleRevisionId.newInstance("org1", "mod1.1", "1+"), false), data);
    assertNotNull(rmr);

    assertEquals(mrid, rmr.getId());
    Date pubdate = new GregorianCalendar(2005, 0, 2, 11, 0, 0).getTime();
    assertEquals(pubdate, rmr.getPublicationDate());
}
 
Example 11
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 12
Source Project: dhis2-core   Source File: DateUtils.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * This method adds days to a date
 *
 * @param date the date.
 * @param days the number of days to add.
 */
public static Date getDateAfterAddition( Date date, int days )
{
    Calendar cal = Calendar.getInstance();

    cal.setTime( date );
    cal.add( Calendar.DATE, days );

    return cal.getTime();
}
 
Example 13
Source Project: mojito   Source File: BoxSDKServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
@Category(BoxSDKTest.class)
public void testSharedFolder() throws BoxSDKServiceException {
    String testFolderId = testFolder.getID();

    BoxFolder folder = boxSDKService.createSharedFolder("testSharedFolder-" + new Date().getTime(), testFolderId);

    BoxSharedLink sharedLink = folder.getInfo().getSharedLink();
    assertNotNull(sharedLink);
    logger.debug("SharedLink Url is: {}", sharedLink.getURL());
}
 
Example 14
Source Project: gocd   Source File: PipelineMaterialRevisionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSetFROMRevisionSameAsTORevisionWhenDependencyMaterial() {
    DependencyMaterial material = new DependencyMaterial(new CaseInsensitiveString("pipeline_name"), new CaseInsensitiveString("stage_name"));

    Modification latestModification = modification(new Date(), "pipeline_name/4/stage_name/1", "4", null);
    MaterialRevision revision = new MaterialRevision(material, latestModification, new Modification(new Date(), "pipeline_name/2/stage_name/1", "2", null));

    PipelineMaterialRevision pmr = new PipelineMaterialRevision(9, revision, null);
    assertThat(pmr.getToModification(), is(latestModification));
    assertThat(pmr.getFromModification(), is(latestModification));
}
 
Example 15
@Test
public void fixedRateWithInitialDelayFirstExecution() {
	Date now = new Date();
	long period = 5000;
	long initialDelay = 30000;
	PeriodicTrigger trigger = new PeriodicTrigger(period);
	trigger.setFixedRate(true);
	trigger.setInitialDelay(initialDelay);
	Date next = trigger.nextExecutionTime(context(null, null, null));
	assertApproximateDifference(now, next, initialDelay);
}
 
Example 16
public static final String getTimestampAsFilenameSuffix(final Date date)
{
  if (date == null) {
    return "--";
  }
  return getFilenameFormatTimestamp(PFUserContext.getTimeZone()).format(date);
}
 
Example 17
Source Project: FoxTelem   Source File: CanPacket.java    License: GNU General Public License v3.0 5 votes vote down vote up
public PcanPacket getPCanPacket(Date createDate) {
	copyBitsToFields();
	if (!isValid()) return null;
	byte[] data = new byte[getLength()];
	for (int i=0; i<getLength(); i++)
		data[i] = (byte) fieldValue[i+CanPacket.ID_BYTES]; // skips the id fields
	
	PcanPacket pcan = new PcanPacket(createDate, id, resets, uptime, type, canId, (byte)getLength(), data);
	return pcan;
}
 
Example 18
Source Project: sakai   Source File: NodeModel.java    License: Educational Community License v2.0 5 votes vote down vote up
private Date getInheritedShoppingPeriodStartDateHelper(NodeModel parent){
	if(parent == null){
		return null;
	}else if(parent.isDirectAccess()){
		return parent.getShoppingPeriodStartDate();
	}else{
		return getInheritedShoppingPeriodStartDateHelper(parent.getParentNode());
	}
}
 
Example 19
Source Project: khs-trouble-maker   Source File: EventService.java    License: Apache License 2.0 5 votes vote down vote up
public void load(String serviceName, String url, int threads) {
	Event event = new Event();
	event.setCreated(new Date());
	event.setAction("LOAD");
	event.setDescription(serviceName.toUpperCase() + " Load of (" + threads + " threads) started at: " + url + " will timeout in " + timeout());
	this.repository.save(event);
	
	sendEvent(event);
}
 
Example 20
Source Project: sakai   Source File: ActivityServiceImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Update the cache with the observed Event
 */
public void update(Observable obs, Object o) {
	if(o instanceof Event){
		Event e = (Event) o;
		
		String userId = e.getUserId();
		
		//If userId is blank, get it from the sessionId.
		//I believe this is always the case though? - sswinsburg.
		if(StringUtils.isBlank(userId)) {
			log.debug("No userId for event, getting from the UsageSession instead: " + e.getEvent());
			
			UsageSession session = usageSessionService.getSession(e.getSessionId());
			if(session != null) {
				userId = session.getUserId();
			}
			
			//if still blank, give up.
			if(StringUtils.isBlank(userId)) {
				log.debug("Couldn't get a userId for event, cannot update cache - skipping: " + e.getEvent());
				return;
			}
		}
		
		//if event is logout, remove entry from cache, otherwise add to cache
		if(StringUtils.equals(e.getEvent(), UsageSessionService.EVENT_LOGOUT)) {
			userActivityCache.remove(userId);
			log.debug("Removed from user activity cache: " + userId);
		} else {
			userActivityCache.put(userId, Long.valueOf(new Date().getTime()));
			log.debug("Added to user activity cache: " + userId);
		}
	}
}
 
Example 21
Source Project: seed   Source File: DateUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据日期获得星期
 * @return 星期日、星期一、星期二、星期三、星期四、星期五、星期六
 */
public static String getWeekName(Date date){
    String[] weekNames = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    int weekNameIndex = calendar.get(Calendar.DAY_OF_WEEK) - 1;
    if(weekNameIndex < 0){
        weekNameIndex = 0;
    }
    return weekNames[weekNameIndex];
}
 
Example 22
Source Project: pay-spring-boot   Source File: PayDateUtil.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 获取上个月最后一天的结束时间,例如2014-07-31 23:59:59
 * 
 * @return 返回上个月最后一天的结束时间
 */
public static Date getLastMonthEndTime() {
    Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MONTH, -1);
    cal.set(Calendar.DAY_OF_MONTH, getDayOfMonth(cal.getTime()));
    return getIntegralEndTime(cal.getTime());
}
 
Example 23
Source Project: seed   Source File: IDCardUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 将15位身份证号码转换为18位
 *
 * @param idCard
 *            15位身份编码
 * @return 18位身份编码
 */
public static String conver15CardTo18(String idCard) {
    String idCard18 = "";
    if (idCard.length() != CHINA_ID_MIN_LENGTH) {
        return null;
    }
    if (isNum(idCard)) {
        // 获取出生年月日
        String birthday = idCard.substring(6, 12);
        Date birthDate = null;
        try {
            birthDate = new SimpleDateFormat("yyMMdd").parse(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        Calendar cal = Calendar.getInstance();
        if (birthDate != null)
            cal.setTime(birthDate);
        // 获取出生年(完全表现形式,如:2010)
        String sYear = String.valueOf(cal.get(Calendar.YEAR));
        idCard18 = idCard.substring(0, 6) + sYear + idCard.substring(8);
        // 转换字符数组
        char[] cArr = idCard18.toCharArray();
        if (cArr != null) {
            int[] iCard = converCharToInt(cArr);
            int iSum17 = getPowerSum(iCard);
            // 获取校验位
            String sVal = getCheckCode18(iSum17);
            if (sVal.length() > 0) {
                idCard18 += sVal;
            } else {
                return null;
            }
        }
    } else {
        return null;
    }
    return idCard18;
}
 
Example 24
Source Project: super-cloudops   Source File: StandardFSCossEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Bucket createBucket(String bucketName) {
	File bucketPath = config.getBucketPath(bucketName);
	isTrue(!bucketPath.exists(), ServerCossException.class, "Duplicate creation directory '%s'", bucketPath);
	bucketPath.mkdirs();
	isTrue(bucketPath.exists(), ServerCossException.class, "Couldn't mkdirs bucket directory to '%s'", bucketPath);
	metadataManager.createBucketMeta(bucketPath.getAbsolutePath());
	setBucketAcl(bucketName, ACL.Default);
	Bucket bucket = new Bucket(bucketName);
	bucket.setCreationDate(new Date());
	bucket.setOwner(getCurrentOwner());
	return bucket;
}
 
Example 25
Source Project: p4ic4idea   Source File: User.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Explicit-value constructor.
 */

public User(String loginName, String email, String fullName,
		Date access, Date update, String password, String jobView,
		UserType type,
		ViewMap<IReviewSubscription> reviewSubscriptions) {
	super(loginName, email, fullName, access, update, type);
	this.password = password;
	this.jobView = jobView;
	this.reviewSubscriptions = reviewSubscriptions;
}
 
Example 26
Source Project: lancoder   Source File: LogFormatter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public String format(LogRecord record) {
    StringBuilder sb = new StringBuilder();

    sb.append(new Date(record.getMillis()))
        .append(" ")
        .append(record.getLevel())
        .append(": ")
        .append(formatMessage(record));

    return sb.toString();
}
 
Example 27
Source Project: spring-microservices   Source File: Article.java    License: MIT License 4 votes vote down vote up
public Date getPublishDate() {
    return publishDate;
}
 
Example 28
Source Project: nexus-public   Source File: Once.java    License: Eclipse Public License 1.0 4 votes vote down vote up
public Date getStartAt() {
  return stringToDate(get(SCHEDULE_START_AT));
}
 
Example 29
Source Project: org.hl7.fhir.core   Source File: Immunization.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @return Date of reaction to the immunization.
 */
public Date getDate() { 
  return this.date == null ? null : this.date.getValue();
}
 
Example 30
Source Project: dx-java   Source File: CardToken.java    License: MIT License 4 votes vote down vote up
public Date getDateLastUpdate() {
    return dateLastUpdate;
}