类java.util.Date源码实例Demo

下面列出了怎么用java.util.Date的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: HIS   文件: BmsInvoiceServiceImpl.java
@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;
}
 
@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);
}
 
源代码3 项目: dss   文件: CAdESLevelTSHA1MessageImprintTest.java
@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());
}
 
源代码4 项目: o2oa   文件: AttendanceDetailServiceAdv.java
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;
}
 
源代码5 项目: lams   文件: NoticeboardContent.java
/** 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>();
   }
 
源代码6 项目: elephant   文件: MessageRequestProcessor.java
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;
}
 
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);
    }
}
 
源代码8 项目: sakai   文件: SignupCalendarHelperImpl.java
@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);
}
 
@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());
}
 
源代码10 项目: ant-ivy   文件: FileSystemResolverTest.java
@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());
}
 
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));
            }
        }
    }
}
 
源代码12 项目: dhis2-core   文件: DateUtils.java
/**
 * 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();
}
 
源代码13 项目: mojito   文件: BoxSDKServiceTest.java
@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());
}
 
源代码14 项目: gocd   文件: PipelineMaterialRevisionTest.java
@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));
}
 
@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);
}
 
源代码16 项目: projectforge-webapp   文件: DateHelper.java
public static final String getTimestampAsFilenameSuffix(final Date date)
{
  if (date == null) {
    return "--";
  }
  return getFilenameFormatTimestamp(PFUserContext.getTimeZone()).format(date);
}
 
源代码17 项目: FoxTelem   文件: CanPacket.java
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;
}
 
源代码18 项目: sakai   文件: NodeModel.java
private Date getInheritedShoppingPeriodStartDateHelper(NodeModel parent){
	if(parent == null){
		return null;
	}else if(parent.isDirectAccess()){
		return parent.getShoppingPeriodStartDate();
	}else{
		return getInheritedShoppingPeriodStartDateHelper(parent.getParentNode());
	}
}
 
源代码19 项目: khs-trouble-maker   文件: EventService.java
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);
}
 
源代码20 项目: sakai   文件: ActivityServiceImpl.java
/**
 * 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);
		}
	}
}
 
源代码21 项目: seed   文件: DateUtil.java
/**
 * 根据日期获得星期
 * @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];
}
 
源代码22 项目: pay-spring-boot   文件: PayDateUtil.java
/**
 * 获取上个月最后一天的结束时间,例如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());
}
 
源代码23 项目: seed   文件: IDCardUtil.java
/**
 * 将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;
}
 
源代码24 项目: super-cloudops   文件: StandardFSCossEndpoint.java
@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;
}
 
源代码25 项目: p4ic4idea   文件: User.java
/**
 * 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;
}
 
源代码26 项目: lancoder   文件: LogFormatter.java
@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();
}
 
源代码27 项目: spring-microservices   文件: Article.java
public Date getPublishDate() {
    return publishDate;
}
 
源代码28 项目: nexus-public   文件: Once.java
public Date getStartAt() {
  return stringToDate(get(SCHEDULE_START_AT));
}
 
源代码29 项目: org.hl7.fhir.core   文件: Immunization.java
/**
 * @return Date of reaction to the immunization.
 */
public Date getDate() { 
  return this.date == null ? null : this.date.getValue();
}
 
源代码30 项目: dx-java   文件: CardToken.java
public Date getDateLastUpdate() {
    return dateLastUpdate;
}
 
 类所在包
 同包方法