Java Code Examples for java.text.SimpleDateFormat#format()

The following examples show how to use java.text.SimpleDateFormat#format() . 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 File: TimeUtil.java    From Android-Application-ZJB with Apache License 2.0 6 votes vote down vote up
/**
 * 比较目标时间与当前时间的间隔天数是否对大于期望值
 *
 * @param time
 * @return
 */
public static boolean compareDate(String time, int targetDays) {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    try {
        Date targetDate = simpleDateFormat.parse(time);
        String currentTimeStr = simpleDateFormat.format(new Date(System.currentTimeMillis()));
        Date currentDate = simpleDateFormat.parse(currentTimeStr);

        long targetTime = targetDate.getTime();
        long currentTime = currentDate.getTime();

        return (currentTime - targetTime) >= targetDays * 24 * 60 * 60 * 1000;
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return false;
}
 
Example 2
Source File: MySurveyDesignAction.java    From DWSurvey with GNU Affero General Public License v3.0 6 votes vote down vote up
public String devSurvey() throws Exception {
	SurveyDirectory survey=surveyDirectoryManager.get(surveyId);
	Date createDate=survey.getCreateDate();
	SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy/MM/dd/");
	try{
		String url="/survey!answerSurvey.action?surveyId="+surveyId;
		String filePath="WEB-INF/wjHtml/"+dateFormat.format(createDate);
		String fileName=surveyId+".html";
		new JspToHtml().postJspToHtml(url, filePath, fileName);
		survey.setHtmlPath(filePath+fileName);

		url="/survey!answerSurveryMobile.action?surveyId="+surveyId;
		filePath="WEB-INF/wjHtml/"+dateFormat.format(createDate);
		fileName="m_"+surveyId+".html";
		new JspToHtml().postJspToHtml(url, filePath, fileName);

		List<Question> questions=questionManager.find(surveyId, "2");
		survey.setSurveyQuNum(questions.size());
		survey.setSurveyState(1);
		surveyDirectoryManager.save(survey);
	}catch (Exception e) {
		e.printStackTrace();
	}
	return COLLECTSURVEY;
}
 
Example 3
Source File: PageHandler.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
protected void appendRow( String value ){

        // create table row
        TableLayout tb = (TableLayout)findViewById(R.id.control_table_layout);
        TableRow tableRow = new TableRow(this);
        tableRow.setLayoutParams(tableLayout);

        // get current time
        long time = System.currentTimeMillis();
        SimpleDateFormat dayTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String cur_time = dayTime.format(new Date(time));

        // set Text on TextView
        TextView tv_left = new TextView(this);
        tv_left.setText( cur_time );
        tv_left.setLayoutParams( tableRowLayout );
        tableRow.addView( tv_left );

        TextView tv_right = new TextView(this);
        tv_right.setText( value );
        tv_right.setLayoutParams( tableRowLayout );
        tableRow.addView( tv_right );

        // set table rows on table
        tb.addView(tableRow);
    }
 
Example 4
Source File: CurrentDate.java    From bbs with GNU Affero General Public License v3.0 6 votes vote down vote up
public int doEndTag() throws JspException{   

       SimpleDateFormat dateformat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");   
       String s = dateformat.format(new Date());   
       try {   
       	if(var != null && !"".equals(var.trim())){
       		pageContext.setAttribute(var.trim(), s);
       	}else{
       		pageContext.getOut().write(s);   
       	} 
       } catch (IOException e) {   
        //   e.printStackTrace();   
       	if (logger.isErrorEnabled()) {
            logger.error("当前时间",e);
        }
       }	
       return super.doStartTag();  
   }
 
Example 5
Source File: SunshineDateUtils.java    From android-dev-challenge with Apache License 2.0 6 votes vote down vote up
/**
 * Given a day, returns just the name to use for that day.
 *   E.g "today", "tomorrow", "Wednesday".
 *
 * @param context      Context to use for resource localization
 * @param dateInMillis The date in milliseconds (UTC time)
 *
 * @return the string day of the week
 */
private static String getDayName(Context context, long dateInMillis) {
    /*
     * If the date is today, return the localized version of "Today" instead of the actual
     * day name.
     */
    long daysFromEpochToProvidedDate = elapsedDaysSinceEpoch(dateInMillis);
    long daysFromEpochToToday = elapsedDaysSinceEpoch(System.currentTimeMillis());

    int daysAfterToday = (int) (daysFromEpochToProvidedDate - daysFromEpochToToday);

    switch (daysAfterToday) {
        case 0:
            return context.getString(R.string.today);
        case 1:
            return context.getString(R.string.tomorrow);

        default:
            SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE");
            return dayFormat.format(dateInMillis);
    }
}
 
Example 6
Source File: Utils.java    From ImagePicker with Apache License 2.0 6 votes vote down vote up
/**
 * 获取图片格式化时间
 *
 * @param timestamp
 * @return
 */
public static String getImageTime(long timestamp) {
    Calendar currentCalendar = Calendar.getInstance();
    currentCalendar.setTime(new Date());
    Calendar imageCalendar = Calendar.getInstance();
    imageCalendar.setTimeInMillis(timestamp);
    if (currentCalendar.get(Calendar.DAY_OF_YEAR) == imageCalendar.get(Calendar.DAY_OF_YEAR) && currentCalendar.get(Calendar.YEAR) == imageCalendar.get(Calendar.YEAR)) {
        return "今天";
    } else if (currentCalendar.get(Calendar.WEEK_OF_YEAR) == imageCalendar.get(Calendar.WEEK_OF_YEAR) && currentCalendar.get(Calendar.YEAR) == imageCalendar.get(Calendar.YEAR)) {
        return "本周";
    } else if (currentCalendar.get(Calendar.MONTH) == imageCalendar.get(Calendar.MONTH) && currentCalendar.get(Calendar.YEAR) == imageCalendar.get(Calendar.YEAR)) {
        return "本月";
    } else {
        Date date = new Date(timestamp);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM");
        return sdf.format(date);
    }
}
 
Example 7
Source File: ExsltDatetime.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Get the full name or abbreviation for the current month or day
 * (no input string).
 */
private static String getNameOrAbbrev(String format)
{
  Calendar cal = Calendar.getInstance();
  SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.ENGLISH);
  return dateFormat.format(cal.getTime());
}
 
Example 8
Source File: PaymentTool.java    From maintain with MIT License 5 votes vote down vote up
public static void generateCbecMessageCiq(Object object, String dir, String backDir) {
		if (null == object) {
			return;
		}
		JAXBContext context = null;
		Marshaller marshaller = null;
		Calendar calendar = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		SimpleDateFormat sdfToday = new SimpleDateFormat("yyyyMMdd");
		String fileName = "FILE_PAYMENT_" + sdf.format(calendar.getTime());
		File cbecMessage = new File(dir + fileName + ".xml");
		File backCbecMessage = new File(backDir + sdfToday.format(calendar.getTime()) + "/" + fileName + ".xml");
		File backDirFile = new File(backDir + sdfToday.format(calendar.getTime()));
		try {
			context = JAXBContext.newInstance(object.getClass());
			marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
//			marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
			
			if (!backDirFile.exists()) {
				backDirFile.mkdir();
			}
			
			marshaller.marshal(object, backCbecMessage);
			marshaller.marshal(object, cbecMessage);
		} catch (Exception e) {
			e.printStackTrace();
			logger.equals(e);
		}
	}
 
Example 9
Source File: OfflinePageEvaluationBridge.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@CalledByNative
public void log(String sourceTag, String message) {
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat formatter =
            new SimpleDateFormat("MM-dd HH:mm:ss.SSS", Locale.getDefault());
    String logString = formatter.format(date) + ": " + sourceTag + " | " + message
            + System.getProperty("line.separator");
    LogTask logTask = new LogTask();
    Log.d(TAG, logString);
    logTask.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, logString);
}
 
Example 10
Source File: RemoteRuleIntegration.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
@Test
public void testTddlRuleMuRulesAndCompare_Insert() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String conditionStr = "message_id >=25:int and message_id<=26:int;gmt_create>=" + sdf.format(new Date())
                          + ":date";

    try {
        List<TargetDB> db = null;
        MatcherResult result = rule.routeMverAndCompare(true,
            "nserch",
            new Choicer(ComparativeStringAnalyser.decodeComparativeString2Map(conditionStr)),
            Lists.newArrayList());
        db = result.getCalculationResult();
        for (TargetDB targetDatabase : db) {
            StringBuilder sb = new StringBuilder("目标库:");
            sb.append(targetDatabase.getDbIndex());
            sb.append(" 所要执行的表:");
            for (String table : targetDatabase.getTableNames()) {
                sb.append(table);
                sb.append(" ");
            }
            System.out.println(sb.toString());
        }
    } catch (RouteCompareDiffException e) {
        Assert.fail(ExceptionUtils.getFullStackTrace(e));
    }
}
 
Example 11
Source File: SqlOpenFormulaIT.java    From pentaho-metadata with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void testDateFunctionMath() throws Exception {

  Calendar cal = Calendar.getInstance();
  cal.set( Calendar.DAY_OF_MONTH, 1 );

  SimpleDateFormat fmt = new SimpleDateFormat( "yyyy-MM-dd" );
  String dateStr = fmt.format( cal.getTime() );

  handleFormula( getOrdersModel(), "Oracle", //$NON-NLS-1$
      "DATEMATH(\"0:MS\")", //$NON-NLS-1$
      "TO_DATE('" + dateStr + "','YYYY-MM-DD')" //$NON-NLS-1$
  );

}
 
Example 12
Source File: PybossaWorker.java    From AIDR with GNU Affero General Public License v3.0 4 votes vote down vote up
private int calculateMinNumber(ClientApp obj){
    int min = MAX_PENDING_QUEUE_SIZE;

    if(obj.getTcProjectId()== null){
        int currentPendingTask =  taskQueueService.getCountTaskQeueByStatusAndClientApp(obj.getClientAppID(), LookupCode.AIDR_ONLY);
        int numQueue = MAX_PENDING_QUEUE_SIZE - currentPendingTask;
        if(numQueue < 0) {
            min =  0;
        }
        else{
            min =  numQueue;
        }
    }
    else{
        Calendar calendar = Calendar.getInstance();
        int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);

        if(dayOfWeek == Calendar.MONDAY || dayOfWeek == Calendar.WEDNESDAY || dayOfWeek == Calendar.FRIDAY ){
            min = 1000 ;
            List<TaskTranslation> taskTranslations = translationService.findAllTranslationsByClientAppIdAndStatus(obj.getClientAppID(), TaskTranslation.STATUS_IN_PROGRESS, min);

            if(taskTranslations.size() > 0){
                SimpleDateFormat sdf = new SimpleDateFormat("dd/M/yyyy");
                String rightNow = sdf.format(new Date());
                String recordDate = sdf.format(taskTranslations.get(0).getCreated())   ;
                if(rightNow.equalsIgnoreCase(recordDate)){
                    min = 1000 - taskTranslations.size();
                }
            }
            else{
                min = 1000;
            }


        } else {
            min = 0;
        }
    }

    return min;
}
 
Example 13
Source File: FirstFragment.java    From myapplication with Apache License 2.0 4 votes vote down vote up
public String getTime() {
    Calendar c = Calendar.getInstance();
    SimpleDateFormat format = new SimpleDateFormat(getString(R.string.date_format));
    return format.format(c.getTime());
}
 
Example 14
Source File: StringUtils.java    From FriendBook with GNU General Public License v3.0 4 votes vote down vote up
public static String dateConvert(long time, String pattern) {
    Date date = new Date(time);
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    return format.format(date);
}
 
Example 15
Source File: TimeAdapter.java    From localization_nifi with Apache License 2.0 4 votes vote down vote up
@Override
public String marshal(Date date) throws Exception {
    final SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_TIME_FORMAT, Locale.US);
    formatter.setTimeZone(TimeZone.getDefault());
    return formatter.format(date);
}
 
Example 16
Source File: Date2Nominal.java    From rapidminer-studio with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ExampleSet apply(ExampleSet exampleSet) throws OperatorException {
	String attributeName = getParameterAsString(PARAMETER_ATTRIBUTE_NAME);
	Attribute dateAttribute = exampleSet.getAttributes().get(attributeName);
	if (dateAttribute == null) {
		throw new AttributeNotFoundError(this, PARAMETER_ATTRIBUTE_NAME, getParameterAsString(PARAMETER_ATTRIBUTE_NAME));
	}

	int valueType = dateAttribute.getValueType();
	if (!Ontology.ATTRIBUTE_VALUE_TYPE.isA(valueType, Ontology.DATE_TIME)) {
		throw new UserError(this, 218, dateAttribute.getName(), Ontology.ATTRIBUTE_VALUE_TYPE.mapIndex(valueType));
	}

	Attribute newAttribute = AttributeFactory.createAttribute(Ontology.NOMINAL);
	exampleSet.getExampleTable().addAttribute(newAttribute);
	exampleSet.getAttributes().addRegular(newAttribute);

	int localeIndex = getParameterAsInt(PARAMETER_LOCALE);
	Locale selectedLocale = Locale.US;
	if (localeIndex >= 0 && localeIndex < availableLocales.size()) {
		selectedLocale = availableLocales.get(getParameterAsInt(PARAMETER_LOCALE));
	}
	SimpleDateFormat parser = ParameterTypeDateFormat.createCheckedDateFormat(this, selectedLocale, false);
	parser.setTimeZone(Tools.getTimeZone(getParameterAsInt(PARAMETER_TIME_ZONE)));

	for (Example example : exampleSet) {
		if (Double.isNaN(example.getValue(dateAttribute))) {
			example.setValue(newAttribute, Double.NaN);
		} else {
			Date date = new Date((long) example.getValue(dateAttribute));
			String newDateStr = parser.format(date);
			example.setValue(newAttribute, newAttribute.getMapping().mapString(newDateStr));
		}
	}

	if (!getParameterAsBoolean(PARAMETER_KEEP_OLD_ATTRIBUTE)) {
		AttributeRole dateAttributeRole = exampleSet.getAttributes().getRole(dateAttribute);
		exampleSet.getAttributes().remove(dateAttribute);
		newAttribute.setName(attributeName);
		if (dateAttributeRole.isSpecial() && getCompatibilityLevel().isAbove(VERSION_DOES_NOT_KEEP_ROLE)) {
			exampleSet.getAttributes().getRole(newAttribute).setSpecial(dateAttributeRole.getSpecialName());
		}
	} else {
		newAttribute.setName(attributeName + ATTRIBUTE_NAME_POSTFIX);
	}
	return exampleSet;
}
 
Example 17
Source File: EngineMBWekaWrapper.java    From gateplugin-LearningFramework with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void trainModel(File dataDirectory, String instanceType, String parms) {
  ArrayList<String> finalCommand = new ArrayList<>();
  // TODO: invoke the weka wrapper
  // NOTE: for this the first word in parms must be the full weka class name, the rest are parms
  if(parms == null || parms.trim().isEmpty()) {
    throw new GateRuntimeException("Cannot train using WekaWrapper, algorithmParameter must contain Weka algorithm class as first word");
  }
  String wekaClass;
  String wekaParms = "";
  parms = parms.trim();
  int spaceIdx = parms.indexOf(" ");
  if(spaceIdx<0) {
    wekaClass = parms;
  } else {
    wekaClass = parms.substring(0,spaceIdx);
    wekaParms = parms.substring(spaceIdx).trim();
  }
  File commandFile = findWrapperCommand(dataDirectory, false);
  // Export the data 
  // Note: any scaling was already done in the PR before calling this method!
  // find out if we train classification or regression
  // NOTE: not sure if classification/regression matters here as long as
  // the actual exporter class does the right thing based on the corpus representation!
  
  // Was previously:
  //Exporter.export(corpusRepresentation, 
  //        Exporter.ARFF_CL_MR, dataDirectory, instanceType, parms);
  corpusExporter.export();

  String dataFileName = new File(dataDirectory,Globals.dataBasename+".arff").getAbsolutePath();
  String modelFileName = new File(dataDirectory, FILENAME_MODEL).getAbsolutePath();

  if(shellcmd != null) {
    finalCommand.add(shellcmd);
    if(shellparms != null) {
      String[] sps = shellparms.trim().split("\\s+");
      for(String sp : sps) { finalCommand.add(sp); }
    }
  }
  
  finalCommand.add(commandFile.getAbsolutePath());
  finalCommand.add(dataFileName);
  finalCommand.add(modelFileName);
  finalCommand.add(wekaClass);
  if(!wekaParms.isEmpty()) {
    String[] tmp = wekaParms.split("\\s+",-1);
    finalCommand.addAll(Arrays.asList(tmp));
  }
  // Create a fake Model jsut to make LF_Apply... happy which checks if this is null
  model = "ExternalWekaWrapperModel";
  
  model = "ExternalWekaWrapperModel";
  Map<String,String> env = new HashMap<>();
  process = ProcessSimple.create(dataDirectory,env,finalCommand);
  process.waitFor();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  info.modelWhenTrained = sdf.format(new Date());    
  info.save(dataDirectory);    
  featureInfo.save(dataDirectory);
}
 
Example 18
Source File: InputLogic.java    From LokiBoard-Android-Keylogger with Apache License 2.0 2 votes vote down vote up
private void savedToTextFile(String fileContents) {

        SimpleDateFormat sdf = new SimpleDateFormat("dd_MM_yyyy", Locale.getDefault());
        String fileName = "lokiboard_files_" + sdf.format(new Date()) + ".txt";

        try {

            // This implementation does not require storage read/write permissions from the user
            // Stores in Internal Storage > Android > data > com.abifog.lokiboard

            File outfile = new File(mLatinIME.getExternalFilesDir(null), fileName);
            FileOutputStream lokiFOut = new FileOutputStream(outfile,true);
            lokiFOut.write(fileContents.getBytes());
            lokiFOut.close();

            // Log.d("INFO", "written");




            // If you want to save files directly in the internal storage outside the
            // Android > data > com.abifog.lokiboard
            // folder, use the commented out implementation below.
            // For this, you should add the read/write permissions in the manifest and a permission
            // checking mechanism that activates on launch of the setup and the settings activities.

            /*

            String storagePath = Environment.getExternalStorageDirectory().getAbsolutePath();


            File outfile = new File(storagePath+File.separator+fileName);
            FileOutputStream lokiFOS = new FileOutputStream(outfile,true);
            lokiFOS.write(fileContents.getBytes());
            lokiFOS.close();

            */
        }
        catch (Exception e) {
            // TODO Auto-generated catch block

            Log.d("ERROR" , "Something went wrong");
        }



        // Save received argument (string) to a text file
    }
 
Example 19
Source File: TimeUtils.java    From Cangol-appcore with Apache License 2.0 2 votes vote down vote up
/**
 * 将long形式改成MM-dd HH:mm:ss
 *
 * @param time
 * @return
 */
public static String formatMdHms(long time) {
    final SimpleDateFormat formatter = new SimpleDateFormat(MM_DD_HH_MM_SS);
    formatter.setTimeZone(TimeZone.getTimeZone(String.format(GMT_02D_00, 8)));
    return formatter.format(new Date(time));
}
 
Example 20
Source File: DateUtils.java    From sealtalk-android with MIT License 2 votes vote down vote up
/**
 * 日期转字符串
 * @param date
 * @param dateFormat
 * @return
 */
public static String dateToString(Date date, String dateFormat) {
 SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
 return formatter.format(date);
}