Java Code Examples for java.text.SimpleDateFormat

The following examples show how to use java.text.SimpleDateFormat. 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: flatpack   Source File: NumericsAndDates.java    License: Apache License 2.0 6 votes vote down vote up
public static void call(final String mapping, final String data) throws Exception {
    // wll provide a clean format for printing the date to the screen
    final SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

    // delimited by a comma
    // text qualified by double quotes
    // ignore first record
    final Parser pzparser = DefaultParserFactory.getInstance().newDelimitedParser(new FileReader(mapping), new FileReader(data), ',', '\"', true);
    final DataSet ds = pzparser.parse();
    // demonstrates the casting abilities of FlatPack
    while (ds.next()) {
        System.out.println("Item Desc: " + ds.getString("ITEM_DESC") + " (String)");
        System.out.println("In Stock: " + ds.getInt("IN_STOCK") + " (int)");
        System.out.println("Price: " + ds.getDouble("PRICE") + " (double)");
        System.out.println("Received Dt: " + sdf.format(ds.getDate("LAST_RECV_DT")) + " (Date)");
        System.out.println("===========================================================================");
    }
}
 
Example 2
private NumericDate getDateForJWTConstruction(BoxAPIException apiException, long secondsSinceResponseDateReceived) {
    NumericDate currentTime;
    List<String> responseDates = apiException.getHeaders().get("Date");

    if (responseDates != null) {
        String responseDate = responseDates.get(0);
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss zzz");
        try {
            Date date = dateFormat.parse(responseDate);
            currentTime = NumericDate.fromMilliseconds(date.getTime());
            currentTime.addSeconds(secondsSinceResponseDateReceived);
        } catch (ParseException e) {
            currentTime = NumericDate.now();
        }
    } else {
        currentTime = NumericDate.now();
    }
    return currentTime;
}
 
Example 3
Source Project: tindroid   Source File: MessagesFragment.java    License: Apache License 2.0 6 votes vote down vote up
private File createImageFile(Activity activity) throws IOException {
    // Create an image file name
    String imageFileName = "IMG_" +
            new SimpleDateFormat("yyMMdd_HHmmss", Locale.getDefault()).format(new Date()) + "_";
    File storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File imageFile = File.createTempFile(
            imageFileName,  // prefix
            ".jpg",  // suffix
            storageDir      // directory
    );

    // Make sure directories exist.
    File path = imageFile.getParentFile();
    if (path != null) {
        path.mkdirs();
    }

    return imageFile;
}
 
Example 4
Source Project: gemfirexd-oss   Source File: GenerateMapper.java    License: Apache License 2.0 6 votes vote down vote up
protected String generateTimestamp(Date baseDate) {

    final SimpleDateFormat formatterTimestamp = new SimpleDateFormat(
        getFormatterTimestamp());
    try {
      baseDate = formatterTimestamp.parse(getBaseTime());
    } catch (ParseException e) {
      e.printStackTrace();
      System.exit(2);
    }

    double addOn = Math.random() * 86400000 * 100;

    long newTime = baseDate.getTime() + (long)addOn;
    Date newDate = new Date(newTime);

    return formatterTimestamp.format(newDate);
  }
 
Example 5
Source Project: vertx-web   Source File: SockJSHandlerImpl.java    License: Apache License 2.0 6 votes vote down vote up
private Handler<RoutingContext> createIFrameHandler(String iframeHTML) {
  String etag = getMD5String(iframeHTML);
  return rc -> {
    try {
      if (log.isTraceEnabled()) log.trace("In Iframe handler");
      if (etag != null && etag.equals(rc.request().getHeader("if-none-match"))) {
        rc.response().setStatusCode(304);
        rc.response().end();
      } else {
        long oneYear = 365 * 24 * 60 * 60 * 1000L;
        String expires = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz").format(new Date(System.currentTimeMillis() + oneYear));
        rc.response()
          .putHeader(HttpHeaders.CONTENT_TYPE, "text/html; charset=UTF-8")
          .putHeader(HttpHeaders.CACHE_CONTROL, "public,max-age=31536000")
          .putHeader(HttpHeaders.EXPIRES, expires)
          .putHeader(HttpHeaders.ETAG, etag)
          .end(iframeHTML);
      }
    } catch (Exception e) {
      log.error("Failed to server iframe", e);
    }
  };
}
 
Example 6
Source Project: xDrip-plus   Source File: SystemStatus.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void setSensorStatus(){
    StringBuilder sensor_status= new StringBuilder();
    if(Sensor.isActive()){
        Sensor sens = Sensor.currentSensor();
        Date date = new Date(sens.started_at);
        DateFormat df = new SimpleDateFormat();
        sensor_status.append(df.format(date));
        sensor_status.append(" (");
        sensor_status.append((System.currentTimeMillis() - sens.started_at) / (1000 * 60 * 60 * 24));
        sensor_status.append("d ");
        sensor_status.append(((System.currentTimeMillis() - sens.started_at) % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        sensor_status.append("h)");
    } else {
        sensor_status.append("not available");
    }
    sensor_status_view.setText(sensor_status.toString());

}
 
Example 7
public static void main(String[] args) {
	String dateString = new Date().toString();

	System.out.println(dateString);
	SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);// MMM
	// dd
	// hh:mm:ss
	// Z
	// yyyy
	// DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL,
	// Locale.getDefault());
	try {
		System.out.println(sdf.parse(dateString));
	} catch (ParseException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}
 
Example 8
Source Project: crypto-bot   Source File: BarMegerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test three tick merge with other timestamps
 * @throws InterruptedException
 * @throws IOException
 * @throws ParseException
 */
@Test(timeout=6000)
public void testTickMerger4() throws InterruptedException, IOException, ParseException {
	
       final SimpleDateFormat parser = new SimpleDateFormat("HH:mm:ss");
       
	final CountDownLatch latch = new CountDownLatch(2);
	
	final BiConsumer<BitfinexCurrencyPair, Bar> tickConsumer = (s, t) -> {
		latch.countDown();
	};
	
	final BarMerger tickMerger = new BarMerger(BitfinexCurrencyPair.BTC_USD, Timeframe.MINUTES_1, tickConsumer);
	tickMerger.addNewPrice(parser.parse("01:01:23").getTime(), new BigDecimal(1.0), new BigDecimal(5.0));
	tickMerger.addNewPrice(parser.parse("01:01:33").getTime(), new BigDecimal(2.0), new BigDecimal(5.0));
	tickMerger.addNewPrice(parser.parse("02:02:53").getTime(), new BigDecimal(2.0), new BigDecimal(5.0));

	tickMerger.close();
	
	latch.await();
}
 
Example 9
Source Project: enkan   Source File: FloatConversionUtil.java    License: Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@link Float}に変換します。
 *
 * @param o
 *            変換元のオブジェクト
 * @param pattern
 *            パターン文字列
 * @return 変換された{@link Float}
 */
public static Float toFloat(final Object o, final String pattern) {
    if (o == null) {
        return null;
    } else if (o instanceof Float) {
        return (Float) o;
    } else if (o instanceof Number) {
        return ((Number) o).floatValue();
    } else if (o instanceof String) {
        return toFloat((String) o);
    } else if (o instanceof java.util.Date) {
        if (pattern != null) {
            return Float.parseFloat(new SimpleDateFormat(pattern).format(o));
        }
        return (float) ((java.util.Date) o).getTime();
    } else {
        return toFloat(o.toString());
    }
}
 
Example 10
Source Project: gemfirexd-oss   Source File: DataGenerator.java    License: Apache License 2.0 6 votes vote down vote up
protected String generateDate(Date baseDate) {

    final SimpleDateFormat formatterTimestamp = new SimpleDateFormat(
        getFormatterTimestamp());
    try {
      baseDate = formatterTimestamp.parse(getBaseTime());
    } catch (ParseException e) {
      e.printStackTrace();
      System.exit(2);
    }

    double addOn = Math.random() * 86400000 * 100;

    long newTime = baseDate.getTime() + (long)addOn;
    Date newDate = new Date(newTime);

    return formatterTimestamp.format(newDate);
  }
 
Example 11
Source Project: quarkus-http   Source File: DefaultAccessLogReceiver.java    License: Apache License 2.0 6 votes vote down vote up
private void calculateChangeOverPoint() {
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.add(Calendar.DATE, 1);
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
    currentDateString = df.format(new Date());
    // if there is an existing default log file, use the date last modified instead of the current date
    if (Files.exists(defaultLogFile)) {
        try {
            currentDateString = df.format(new Date(Files.getLastModifiedTime(defaultLogFile).toMillis()));
        } catch(IOException e){
            // ignore. use the current date if exception happens.
        }
    }
    changeOverPoint = calendar.getTimeInMillis();
}
 
Example 12
Source Project: hadoop-gpu   Source File: MiniMRCluster.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create the job tracker and run it.
 */
public void run() {
  try {
    jc = (jc == null) ? createJobConf() : createJobConf(jc);
    File f = new File("build/test/mapred/local").getAbsoluteFile();
    jc.set("mapred.local.dir",f.getAbsolutePath());
    jc.setClass("topology.node.switch.mapping.impl", 
        StaticMapping.class, DNSToSwitchMapping.class);
    String id = 
      new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    tracker = JobTracker.startTracker(jc, id);
    tracker.offerService();
  } catch (Throwable e) {
    LOG.error("Job tracker crashed", e);
    isActive = false;
  }
}
 
Example 13
Source Project: journaldev   Source File: DateFormatter.java    License: MIT License 6 votes vote down vote up
/**
 * Utility function to convert java Date to TimeZone format
 * @param date
 * @param format
 * @param timeZone
 * @return
 */
public static String formatDateToString(Date date, String format,
		String timeZone) {
	// null check
	if (date == null) return null;
	// create SimpleDateFormat object with input format
	SimpleDateFormat sdf = new SimpleDateFormat(format);
	// default system timezone if passed null or empty
	if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) {
		timeZone = Calendar.getInstance().getTimeZone().getID();
	}
	// set timezone to SimpleDateFormat
	sdf.setTimeZone(TimeZone.getTimeZone(timeZone));
	// return Date in required format with timezone as String
	return sdf.format(date);
}
 
Example 14
Source Project: oxTrust   Source File: StatusCheckerTimer.java    License: MIT License 6 votes vote down vote up
private void getFacterBandwidth(String facterResult, ConfigurationStatus configuration) {
	log.debug("Setting bandwidth attributes");
	if (facterResult != null) {
		String[] lines = facterResult.split("\n");
		SimpleDateFormat monthFormat = new SimpleDateFormat("MMM ''yy");
		String month = monthFormat.format(new Date());
		Pattern curent = Pattern.compile("^\\s*" + month);

		for (String line : lines) {
			Matcher match = curent.matcher(line);
			if (match.find()) {
				line = line.replaceAll("^\\s*" + month, "");
				String[] values = line.split("\\|");
				configuration.setGluuBandwidthRX(values[0].replaceAll("^\\s*", "").replaceAll("\\s*$", ""));
				configuration.setGluuBandwidthTX(values[1].replaceAll("^\\s*", "").replaceAll("\\s*$", ""));
			}
		}
	} else {
		configuration.setGluuBandwidthRX("-1");
		configuration.setGluuBandwidthTX("-1");
	}

}
 
Example 15
Source Project: Dendroid-HTTP-RAT   Source File: VideoView.java    License: GNU General Public License v3.0 5 votes vote down vote up
public InputStream getInputStreamFromUrl(String urlBase, String urlData) throws UnsupportedEncodingException {
    	
//    	Log.d("com.connect", urlBase);
//    	Log.d("com.connect", urlData);

    	String urlDataFormatted=urlData;
    	
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH:mm:ss");
        String currentDateandTime = "[" + sdf.format(new Date()) + "] - ";
        currentDateandTime = URLEncoder.encode (currentDateandTime, "UTF-8");

        if(urlData.length()>1)
        {
        Log.d("com.connect", urlBase + urlData);

    	urlData = currentDateandTime + URLEncoder.encode (urlData, "UTF-8");
    	urlDataFormatted = urlData.replaceAll("\\.", "~period");
    	
    	Log.d("com.connect", urlBase + urlDataFormatted);
        }

    	  InputStream content = null;
      	if(isNetworkAvailable())
      	{
      	  try 
      	  {
      	    Log.i("com.connect", "network push POST");
      	    HttpClient httpclient = new DefaultHttpClient();
      	    HttpResponse response = httpclient.execute(new HttpGet(urlBase + urlDataFormatted));
      	    content = response.getEntity().getContent();
      	    httpclient.getConnectionManager().shutdown();
      	  } catch (Exception e) {
      		  Log.e("com.connect", "exception", e);
      	  }
      	    return content;
      	}
  		return null;
    }
 
Example 16
Source Project: artemis   Source File: StatusServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private GetLeasesStatusResponse getLeasesStatus(String opName, final String traceKey, final GetLeasesStatusRequest request,
        final LeaseManager<Instance> leaseManager) {
    if (_rateLimiter.isRateLimited(opName))
        return new GetLeasesStatusResponse(0, 0, 0, false, false, 0, null, ResponseStatusUtil.RATE_LIMITED_STATUS);

    try {
        return ArtemisTraceExecutor.INSTANCE.execute(traceKey, new Func<GetLeasesStatusResponse>() {
            @Override
            public GetLeasesStatusResponse execute() {
                Map<Service, List<LeaseStatus>> leasesStatusMap = new HashMap<>();
                List<String> serviceIds = request.getServiceIds();
                ListMultimap<Service, Lease<Instance>> leaseMultiMap = CollectionValues.isNullOrEmpty(serviceIds)
                        ? _registryRepository.getLeases(leaseManager) : _registryRepository.getLeases(serviceIds, leaseManager);
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
                int leaseCount = 0;
                for (Service service : leaseMultiMap.keySet()) {
                    List<LeaseStatus> leasesStatus = new ArrayList<>();
                    List<Lease<Instance>> leases = leaseMultiMap.get(service);
                    for (Lease<Instance> lease : leases) {
                        leasesStatus.add(new LeaseStatus(lease.data().toString(), dateFormat.format(lease.creationTime()),
                                dateFormat.format(lease.renewalTime()), dateFormat.format(lease.evictionTime()), lease.ttl()));
                    }

                    leasesStatusMap.put(service, leasesStatus);
                    leaseCount += leasesStatus.size();
                }

                LeaseUpdateSafeChecker leaseUpdateSafeChecker = leaseManager.leaseUpdateSafeChecker();
                return new GetLeasesStatusResponse(leaseUpdateSafeChecker.maxCount(), leaseUpdateSafeChecker.maxCountLastUpdateTime(),
                        leaseUpdateSafeChecker.countLastTimeWindow(), leaseUpdateSafeChecker.isSafe(), leaseUpdateSafeChecker.isEnabled(),
                        leaseCount, leasesStatusMap, ResponseStatusUtil.SUCCESS_STATUS);
            }
        });
    } catch (Throwable ex) {
        _logger.warn("GetLeasesStatus failed. request: " + request, ex);
        return new GetLeasesStatusResponse(0, 0, 0, false, false, 0, null,
                ResponseStatusUtil.newFailStatus(ex.getMessage(), ErrorCodes.INTERNAL_SERVICE_ERROR));
    }
}
 
Example 17
Source Project: ha-bridge   Source File: HueConfig.java    License: Apache License 2.0 5 votes vote down vote up
public static HueConfig createConfig(String name, String ipaddress, Map<String, WhitelistEntry> awhitelist, String emulateHubVersion, boolean isLinkButtonPressed, String emulateMAC) {
	HueConfig aConfig = new HueConfig();
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
	dateFormatGmt.setTimeZone(TimeZone.getTimeZone("UTC"));
	aConfig.setMac(HueConfig.getMacAddress(ipaddress));
	aConfig.setApiversion(HueConstants.API_VERSION);
	aConfig.setPortalservices(false);
	aConfig.setGateway(ipaddress);
	aConfig.setSwversion(emulateHubVersion);
	aConfig.setLinkbutton(isLinkButtonPressed);
	aConfig.setIpaddress(ipaddress);
	aConfig.setProxyport(0);
	aConfig.setSwupdate(Swupdate.createSwupdate());
	aConfig.setNetmask("255.255.255.0");
	aConfig.setName(name);
	aConfig.setDhcp(true);
	aConfig.setUtc(dateFormatGmt.format(new Date()));
	aConfig.setProxyaddress("none");
	aConfig.setLocaltime(dateFormat.format(new Date()));
	aConfig.setTimezone(TimeZone.getDefault().getID());
	aConfig.setZigbeechannel("6");
	aConfig.setBridgeid(HuePublicConfig.createConfig(name, ipaddress, emulateHubVersion, emulateMAC).getHueBridgeIdFromMac());
	aConfig.setModelid(HueConstants.MODEL_ID);
	aConfig.setFactorynew(false);
	aConfig.setReplacesbridgeid(null);
	aConfig.setWhitelist(awhitelist);

	return aConfig;
}
 
Example 18
Source Project: WeSync   Source File: StatusPanel.java    License: MIT License 5 votes vote down vote up
/**
 * 获取指定时间对应的毫秒数
 *
 * @param time "HH:mm:ss"
 * @return
 */
private static long getTimeMillis(String time) {
    try {
        DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
        DateFormat dayFormat = new SimpleDateFormat("yy-MM-dd");
        Date curDate = dateFormat.parse(dayFormat.format(new Date()) + " " + time);
        return curDate.getTime();
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return 0;
}
 
Example 19
@Before
public void init() throws ParseException {
    metric = "test";
    String strDate = "2017-08-01 13:14:15";
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    time = sdf.parse(strDate).getTime();
}
 
Example 20
Source Project: astor   Source File: TimeSeriesChartDemo1.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates a chart.
 * 
 * @param dataset  a dataset.
 * 
 * @return A chart.
 */
private static JFreeChart createChart(XYDataset dataset) {

    JFreeChart chart = ChartFactory.createTimeSeriesChart(
        "Legal & General Unit Trust Prices",  // title
        "Date",             // x-axis label
        "Price Per Unit",   // y-axis label
        dataset,            // data
        true,               // create legend?
        true,               // generate tooltips?
        false               // generate URLs?
    );

    chart.setBackgroundPaint(Color.white);

    XYPlot plot = (XYPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.lightGray);
    plot.setDomainGridlinePaint(Color.white);
    plot.setRangeGridlinePaint(Color.white);
    plot.setAxisOffset(new RectangleInsets(5.0, 5.0, 5.0, 5.0));
    plot.setDomainCrosshairVisible(true);
    plot.setRangeCrosshairVisible(true);
    
    XYItemRenderer r = plot.getRenderer();
    if (r instanceof XYLineAndShapeRenderer) {
        XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
        renderer.setBaseShapesVisible(true);
        renderer.setBaseShapesFilled(true);
    }
    
    DateAxis axis = (DateAxis) plot.getDomainAxis();
    axis.setDateFormatOverride(new SimpleDateFormat("MMM-yyyy"));
    
    return chart;

}
 
Example 21
@Override
public Component getTableCellRendererComponent(JTable table,
		Object value, boolean isSelected, boolean hasFocus,
		int row, int column) {
	JLabel label = (JLabel)super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
			row, column);
	
	label.setText(SimpleDateFormat.getDateTimeInstance().format((Date)value));
	
	return label;
}
 
Example 22
Source Project: PoseidonX   Source File: FlinkEngineController.java    License: Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping(value = "/getTaskManagersByTaskId", method = RequestMethod.POST)
public List<FlinkTaskManagerDTO>  getTaskManagersByTaskId(Integer taskId) throws Exception{
    List<FlinkTaskManagerDTO> taskManagerDTOs = Lists.newArrayList();
    FlinkTaskDetailDTO flinkTaskDetailDTO = getFlinkTaskDetailDto(taskId);
    if (flinkTaskDetailDTO == null){
        return taskManagerDTOs;
    }
    if(CollectionUtils.isEmpty(flinkTaskDetailDTO.getTaskManagers())){
        return taskManagerDTOs;
    }
    for(String taskManager:flinkTaskDetailDTO.getTaskManagers()){
        JSONObject taskManagerJsonObject = JSONObject.parseObject(taskManager);
        List<FlinkTaskManagerDTO> flinkTaskManagerDTOs = JSONObject.parseArray(taskManagerJsonObject.getString("taskmanagers"),FlinkTaskManagerDTO.class);
        if(CollectionUtils.isNotEmpty(flinkTaskManagerDTOs)){
            FlinkTaskManagerDTO flinkTaskManagerDTO = flinkTaskManagerDTOs.get(0);

            flinkTaskManagerDTO.setLastHeartbeat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(flinkTaskManagerDTO.getTimeSinceLastHeartbeat()));
            flinkTaskManagerDTO.setPhysicalMemoryShow( formetFileSize( flinkTaskManagerDTO.getPhysicalMemory()));
            flinkTaskManagerDTO.setFreeMemoryShow( formetFileSize( flinkTaskManagerDTO.getFreeMemory()));
            flinkTaskManagerDTO.setManagedMemoryShow( formetFileSize( flinkTaskManagerDTO.getManagedMemory()));
            flinkTaskManagerDTO.setPhysicalMemoryShow( formetFileSize( flinkTaskManagerDTO.getPhysicalMemory()));
            taskManagerDTOs.add(flinkTaskManagerDTO);
        }
    }
    return taskManagerDTOs;
}
 
Example 23
public IDEAFormatter(String formatOfTime) {
    String formatStr = formatOfTime;
    if (TextUtils.isEmpty(formatStr)) {
        formatStr = DATE_FORMAT;
    }

    mFormatter = new SimpleDateFormat(formatStr);
}
 
Example 24
Source Project: SmsCode   Source File: BackupManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String getDefaultBackupFilename() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmm", Locale.getDefault());
    String dateStr = sdf.format(new Date());
    File backupDir = getBackupDir();
    String basename = BACKUP_FILE_NAME_PREFIX + dateStr;
    String filename = basename + BACKUP_FILE_EXTENSION;
    for (int i = 2; new File(backupDir, filename).exists(); i++) {
        filename = basename + "-" + i + BACKUP_FILE_EXTENSION;
    }
    return filename;
}
 
Example 25
@Test
public void testDepositionDate() throws ParseException {

	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
	Date depositionDate = dateFormat.parse("1992-03-12");
	assertEquals(depositionDate, s.getPDBHeader().getDepDate());

}
 
Example 26
Source Project: ezScrum   Source File: TestTool.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 計算該Sprint的最後一天,包含週末。
 * 
 * @param dueDate
 * @return
 */
public String calcaulateDueDate(int inter, Date startDate) {
	String dueDateString;
	int interval = inter;
	SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
	Calendar calendar = Calendar.getInstance();
	calendar.setTime(startDate);
	calendar.add(Calendar.DATE, interval * 7 - 1);
	Date dueDate = calendar.getTime();
	dueDateString = simpleDateFormat.format(dueDate);
	return dueDateString;
}
 
Example 27
Source Project: dubbox   Source File: DateUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 *
 * 字符串形式转化为Date类型 String类型按照format格式转为Date类型
 **/
public static Date fromStringToDate(String format, String dateTime) throws ParseException {
	Date date = null;
	SimpleDateFormat sdf = new SimpleDateFormat(format);
	date = sdf.parse(dateTime);
	return date;
}
 
Example 28
Source Project: jdk8u60   Source File: HttpCookie.java    License: GNU General Public License v2.0 5 votes vote down vote up
private long expiryDate2DeltaSeconds(String dateString) {
    Calendar cal = new GregorianCalendar(GMT);
    for (int i = 0; i < COOKIE_DATE_FORMATS.length; i++) {
        SimpleDateFormat df = new SimpleDateFormat(COOKIE_DATE_FORMATS[i],
                                                   Locale.US);
        cal.set(1970, 0, 1, 0, 0, 0);
        df.setTimeZone(GMT);
        df.setLenient(false);
        df.set2DigitYearStart(cal.getTime());
        try {
            cal.setTime(df.parse(dateString));
            if (!COOKIE_DATE_FORMATS[i].contains("yyyy")) {
                // 2-digit years following the standard set
                // out it rfc 6265
                int year = cal.get(Calendar.YEAR);
                year %= 100;
                if (year < 70) {
                    year += 2000;
                } else {
                    year += 1900;
                }
                cal.set(Calendar.YEAR, year);
            }
            return (cal.getTimeInMillis() - whenCreated) / 1000;
        } catch (Exception e) {
            // Ignore, try the next date format
        }
    }
    return 0;
}
 
Example 29
/**
 * Returns todays date as int in the form of yyyyMMdd
 * @return Today as in id
 */
private int getTodayAsID() {
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    String concatDate = dateFormat.format(new Date());

    return Integer.parseInt(concatDate);
}
 
Example 30
Source Project: common-utils   Source File: DateUtil.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 将字符串转换成日期对象
 * 
 * @param sDate 日期字符串
 * @param format 日期格式 @see DateFormat
 * @param defaultValue 默认值
 * @return 日期对象,如果格式化失败则返回默认值<code>defaultValue</code>
 */
public static Date parseDate(String sDate, String format, Date defaultValue) {
    if (StringUtil.isBlank(sDate) || StringUtil.isBlank(format)) {
        return defaultValue;
    }

    DateFormat formatter = new SimpleDateFormat(format);
    try {
        return formatter.parse(sDate);
    } catch (ParseException e) {
        return defaultValue;
    }

}