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 check out the related API usage on the sidebar.
Example 1
Source Project: flatpack   Source File: NumericsAndDates.java    License: Apache License 2.0 5 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 5 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 5 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 5 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 5 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
Source Project: satstat   Source File: RemoteDirListTask.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
protected RemoteFile[] doInBackground(String... params) {
	Uri uri = Uri.parse(params[0]);
	RemoteFile[] rfiles = null;
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
	df.setTimeZone(TimeZone.getDefault());
	if (uri.getScheme() == null)
		return null;
	if (uri.getScheme().equals("http") || uri.getScheme().equals("https"))
		rfiles = HttpDownloader.list(params[0]);
	
	if (rfiles == null)
		Log.w(TAG, "Error – could not retrieve content!");
	else if (rfiles.length == 0)
		Log.w(TAG, "Remote directory is empty.");
	/*
	else {
		Log.d(TAG, "Remote directory contents:");
		for (RemoteFile rf : rfiles)
			Log.d(TAG, String.format("\n\t%s \t%s \t%s \t%s",
				rf.isDirectory ? "D" : "F",
				df.format(new Date(rf.timestamp)),
				rf.getFriendlySize(),
				rf.name));
	}
	 */
	return rfiles;
}
 
Example 8
Source Project: seldon-server   Source File: JobUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static long dateToUnixDays(String dateString) throws ParseException {
    DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    Date date = dateFormat.parse(dateString);

    return ((date.getTime() / 1000) / 86400);
}
 
Example 9
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 10
Source Project: SimFix   Source File: 1_FastDateFormat.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * <p>Gets a date formatter instance using the specified style, time
 * zone and locale.</p>
 * 
 * @param style  date style: FULL, LONG, MEDIUM, or SHORT
 * @param timeZone  optional time zone, overrides time zone of
 *  formatted date
 * @param locale  optional locale, overrides system locale
 * @return a localized standard date formatter
 * @throws IllegalArgumentException if the Locale has no date
 *  pattern defined
 */
public static synchronized FastDateFormat getDateInstance(int style, TimeZone timeZone, Locale locale) {
    Object key = new Integer(style);
    if (timeZone != null) {
        key = new Pair(key, timeZone);
    }

    if (locale != null) {
        key = new Pair(key, locale);
    }


    FastDateFormat format = (FastDateFormat) cDateInstanceCache.get(key);
    if (format == null) {
        if (locale == null) {
            locale = Locale.getDefault();
        }
        try {
            SimpleDateFormat formatter = (SimpleDateFormat) DateFormat.getDateInstance(style, locale);
            String pattern = formatter.toPattern();
            format = getInstance(pattern, timeZone, locale);
            cDateInstanceCache.put(key, format);
            
        } catch (ClassCastException ex) {
            throw new IllegalArgumentException("No date pattern for locale: " + locale);
        }
    }
    return format;
}
 
Example 11
Source Project: L2jBrasil   Source File: PetitionManager.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void viewPetition(L2PcInstance activeChar, int petitionId)
{
	if (!activeChar.isGM())
		return;

	if (!isValidPetition(petitionId))
		return;

	Petition currPetition = getPendingPetitions().get(petitionId);
       StringBuilder htmlContent = new StringBuilder("<html><body>");
	SimpleDateFormat dateFormat = new SimpleDateFormat("EEE dd MMM HH:mm z");

	htmlContent.append("<center><br><font color=\"LEVEL\">Petition #" + currPetition.getId() + "</font><br1>");
	htmlContent.append("<img src=\"L2UI.SquareGray\" width=\"200\" height=\"1\"></center><br>");
	htmlContent.append("Submit Time: " + dateFormat.format(new Date(currPetition.getSubmitTime())) + "<br1>");
	htmlContent.append("Petitioner: " + currPetition.getPetitioner().getName() + "<br1>");
	htmlContent.append("Petition Type: " + currPetition.getTypeAsString() + "<br>" + currPetition.getContent() + "<br>");
	htmlContent.append("<center><button value=\"Accept\" action=\"bypass -h admin_accept_petition " + currPetition.getId() + "\"" +
	"width=\"50\" height=\"15\" back=\"sek.cbui94\" fore=\"sek.cbui92\"><br1>");
	htmlContent.append("<button value=\"Reject\" action=\"bypass -h admin_reject_petition " + currPetition.getId() + "\" " +
	"width=\"50\" height=\"15\" back=\"sek.cbui94\" fore=\"sek.cbui92\"><br>");
	htmlContent.append("<button value=\"Back\" action=\"bypass -h admin_view_petitions\" width=\"40\" height=\"15\" back=\"sek.cbui94\" " +
	"fore=\"sek.cbui92\"></center>");
	htmlContent.append("</body></html>");

	NpcHtmlMessage htmlMsg = new NpcHtmlMessage(0);
	htmlMsg.setHtml(htmlContent.toString());
	activeChar.sendPacket(htmlMsg);
}
 
Example 12
Source Project: rcloneExplorer   Source File: FileItem.java    License: MIT License 5 votes vote down vote up
private long modTimeZonedToMillis(String modTime) {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
    int index = modTime.lastIndexOf("+");
    if (index == -1) {
        index = modTime.lastIndexOf("-");
    }
    int fractionIndex = modTime.indexOf('.');
    String reducedString = fractionIndex == -1 ? modTime : modTime.substring(0, fractionIndex) + modTime.substring(index);
    try {
        return format.parse(reducedString).getTime();
    } catch (ParseException e) {
        return 0L;
    }
}
 
Example 13
Source Project: crypto-bot   Source File: BarMegerTest.java    License: Apache License 2.0 5 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 14
public void applyLocaleSettings( final LocaleSettings localeSettings ) {
  final SimpleDateFormat isoDateFormat = createSafely( localeSettings.getDatetimeFormatPattern(),
    WorkspaceSettings.DATETIME_FORMAT_DEFAULT, localeSettings.getLocale() );
  final TimeZone timeZone = localeSettings.getTimeZone();
  isoDateFormat.setTimeZone( timeZone );
  setDefaultRenderer( Date.class, new FormattingTableCellRenderer( isoDateFormat ) );
  setDefaultRenderer( Timestamp.class, new FormattingTableCellRenderer( isoDateFormat ) );

  final DateCellEditor dateCellEditor = new DateCellEditor( Date.class );
  dateCellEditor.setDateFormat( isoDateFormat );
  setDefaultEditor( Date.class, dateCellEditor );

  final DateCellEditor timestampEditor = new DateCellEditor( Timestamp.class );
  timestampEditor.setDateFormat( isoDateFormat );
  setDefaultEditor( Timestamp.class, timestampEditor );

  final SimpleDateFormat dateFormat = createSafely( localeSettings.getDateFormatPattern(),
    WorkspaceSettings.DATE_FORMAT_DEFAULT, localeSettings.getLocale() );
  dateFormat.setTimeZone( timeZone );
  setDefaultRenderer( java.sql.Date.class, new FormattingTableCellRenderer( dateFormat ) );

  final DateCellEditor sqlDateCellEditor = new DateCellEditor( java.sql.Date.class );
  sqlDateCellEditor.setDateFormat( dateFormat );
  setDefaultEditor( java.sql.Date.class, sqlDateCellEditor );

  final SimpleDateFormat timeFormat = createSafely( localeSettings.getTimeFormatPattern(),
    WorkspaceSettings.TIME_FORMAT_DEFAULT, localeSettings.getLocale() );
  timeFormat.setTimeZone( timeZone );
  setDefaultRenderer( Time.class, new FormattingTableCellRenderer( timeFormat ) );

  final TimeCellEditor timeCellEditor = new TimeCellEditor( Time.class );
  timeCellEditor.setDateFormat( timeFormat );
  setDefaultEditor( Time.class, timeCellEditor );
}
 
Example 15
Source Project: enkan   Source File: FloatConversionUtil.java    License: Eclipse Public License 1.0 5 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 16
Source Project: pacbot   Source File: CommonUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Date format.
 *
 * @param dateInString the date in string
 * @param formatFrom the format from
 * @param formatTo the format to
 * @return the date
 * @throws ParseException the parse exception
 */
public static Date dateFormat(final String dateInString, String formatFrom, String formatTo)
        throws java.text.ParseException {
    String dateDormatter = "MM/dd/yyyy";
    if (StringUtils.isNullOrEmpty(formatFrom)) {
        formatFrom = dateDormatter;
    }
    if (StringUtils.isNullOrEmpty(formatTo)) {
        formatTo = dateDormatter;
    }
    DateFormat dateFromFormater = new SimpleDateFormat(formatFrom);
    DateFormat dateToFormater = new SimpleDateFormat(formatTo);
    return dateToFormater.parse(dateToFormater.format(dateFromFormater.parse(dateInString)));
}
 
Example 17
Source Project: training   Source File: CoursesController.java    License: MIT License 5 votes vote down vote up
private Course mapToEntity(CourseDto dto) throws ParseException {
	Course newEntity = new Course();
	newEntity.setName(dto.name);
	newEntity.setStartDate(new SimpleDateFormat("dd-MM-yyyy").parse(dto.startDate));
	newEntity.setDescription(dto.description); // SOLUTION
	newEntity.setTeacher(teacherRepo.getById(dto.teacherId));
	return newEntity;
}
 
Example 18
Source Project: citygml4j   Source File: MissingSchemaReference.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	SimpleDateFormat df = new SimpleDateFormat("[HH:mm:ss] "); 

	System.out.println(df.format(new Date()) + "setting up citygml4j context and CityGML builder");
	CityGMLContext ctx = CityGMLContext.getInstance();
	CityGMLBuilder builder = ctx.createCityGMLBuilder();

	System.out.println(df.format(new Date()) + "setting up schema handler");
	SchemaHandler schemaHandler = SchemaHandler.newInstance();
	schemaHandler.setSchemaEntityResolver(new SchemaEntityResolver());
	schemaHandler.setErrorHandler(new SchemaParseErrorHandler());

	System.out.println(df.format(new Date()) + "reading ADE-enriched CityGML file LOD0_Railway_NoiseADE_missing_ADE_reference_v200.gml");
	System.out.println(df.format(new Date()) + "note: the input document is lacking a reference to the ADE schema document");
	CityGMLInputFactory in = builder.createCityGMLInputFactory(schemaHandler);
	in.setProperty(CityGMLInputFactory.FEATURE_READ_MODE, FeatureReadMode.SPLIT_PER_FEATURE);
	
	CityGMLReader reader = in.createCityGMLReader(new File("datasets/LOD0_Railway_NoiseADE_missing_ADE_reference_v200.gml"));
	
	while (reader.hasNext()) {
		CityGML citygml = reader.nextFeature();
		
		if (citygml instanceof AbstractFeature)
			System.out.println("Found CityGML: " + citygml.getCityGMLClass());
		else if (citygml instanceof ADEGenericElement)
			System.out.println("Found ADE: " + ((ADEGenericElement)citygml).getContent().getLocalName());
	}
	
	reader.close();
	System.out.println(df.format(new Date()) + "sample citygml4j application successfully finished");
}
 
Example 19
Source Project: gemfirexd-oss   Source File: DataGenerator.java    License: Apache License 2.0 5 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 20
Source Project: quarkus-http   Source File: DefaultAccessLogReceiver.java    License: Apache License 2.0 5 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 21
Source Project: android_9.0.0_r45   Source File: DateFormat.java    License: Apache License 2.0 5 votes vote down vote up
private static String getDateFormatString(Context context) {
    final Locale locale = context.getResources().getConfiguration().locale;
    java.text.DateFormat df = java.text.DateFormat.getDateInstance(
            java.text.DateFormat.SHORT, locale);
    if (df instanceof SimpleDateFormat) {
        return ((SimpleDateFormat) df).toPattern();
    }

    throw new AssertionError("!(df instanceof SimpleDateFormat)");
}
 
Example 22
Source Project: hadoop-gpu   Source File: MiniMRCluster.java    License: Apache License 2.0 5 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 23
Source Project: journaldev   Source File: DateFormatter.java    License: MIT License 5 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 24
private int getEntityHour(ReportEntity reportEntity) {
    String string_timestamp = reportEntity.getTimeStamp();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    Date entity_date = null;
    try {
        entity_date = sdf.parse(string_timestamp);
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return entity_date.getHours();
}
 
Example 25
Source Project: tmxeditor8   Source File: StringUtilsBasic.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * 判断字符串是否为日期
 * @param str
 * 			要判断的字符串
 * @param format
 * 			日期格式,按该格式检查字符串
 * @return boolean
 * 			符合为true,不符合为false
 */
public static boolean isDate(String str, String format) {
	if (hasLength(str)) {
		SimpleDateFormat formatter = new SimpleDateFormat(format);
		formatter.setLenient(false);
		try {
			formatter.format(formatter.parse(str));
		} catch (Exception e) {
			return false;
		}
		return true;
	}
	return false;
}
 
Example 26
Source Project: das   Source File: DateUtil.java    License: Apache License 2.0 5 votes vote down vote up
final public static int str2Int(String fromat, String time) {
    SimpleDateFormat df = DateUtil.getSdf(fromat);//yyyy-MM-dd HH:mm:ss
    SimpleDateFormat sdf = DateUtil.getSdf(DATE_FORMAT_INT);
    Calendar cal = Calendar.getInstance();
    try {
        if (null != time && time.length() > 5) {
            Date date = df.parse(time);
            cal.setTime(date);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return Integer.valueOf(sdf.format(cal.getTime()));
}
 
Example 27
Source Project: mycore   Source File: MCRGenericPIGenerator.java    License: GNU General Public License v3.0 5 votes vote down vote up
MCRGenericPIGenerator(String id, String generalPattern, SimpleDateFormat dateFormat,
    String objectTypeMapping, String objectProjectMapping,
    int countPrecision, String type, String... xpaths) {
    super(id);
    setObjectProjectMapping(objectProjectMapping);
    setGeneralPattern(generalPattern);
    setDateFormat(dateFormat);
    setObjectTypeMapping(objectTypeMapping);
    setCountPrecision(countPrecision);
    setType(type);
    validateProperties();
    setXpath(xpaths);
}
 
Example 28
Source Project: blackduck-alert   Source File: DateUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static OffsetDateTime parseDate(String dateTime, String format) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat(format);
    try {
        Date parsedDate = sdf.parse(dateTime);
        return fromDateUTC(parsedDate);
    } catch (DateTimeParseException e) {
        throw new ParseException(e.getParsedString(), e.getErrorIndex());
    }
}
 
Example 29
Source Project: Newslly   Source File: Article.java    License: MIT License 5 votes vote down vote up
public Date getDate() {

        try {

            SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            simpleDateFormat1.setTimeZone(TimeZone.getTimeZone("UTC"));
            date = simpleDateFormat1.parse(publishedAt.substring(0, 18).replace("-", "/").replace("T", " "));
        }
        catch (Exception e){
            e.printStackTrace();
        };
        System.out.println("date check1 "+date);
        return date;
    }
 
Example 30
Source Project: framework   Source File: ODateUtils.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Returns date before given days
 *
 * @param days days to before
 * @return string date string before days
 */
public static String getDateBefore(int days) {
    Date today = new Date();
    Calendar cal = new GregorianCalendar();
    cal.setTime(today);
    cal.add(Calendar.DAY_OF_MONTH, days * -1);
    Date date = cal.getTime();
    SimpleDateFormat gmtFormat = new SimpleDateFormat();
    gmtFormat.applyPattern("yyyy-MM-dd 00:00:00");
    TimeZone gmtTime = TimeZone.getTimeZone("GMT");
    gmtFormat.setTimeZone(gmtTime);
    return gmtFormat.format(date);
}