下面列出了java.text.SimpleDateFormat#format ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
/**
* 获取图片格式化时间
*
* @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);
}
}
/**
* 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);
}
}
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();
}
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;
}
/**
* 比较目标时间与当前时间的间隔天数是否对大于期望值
*
* @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;
}
@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$
);
}
@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));
}
}
@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);
}
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);
}
}
/**
* 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());
}
@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;
}
@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);
}
public static String dateConvert(long time, String pattern) {
Date date = new Date(time);
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.format(date);
}
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;
}
public String getTime() {
Calendar c = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat(getString(R.string.date_format));
return format.format(c.getTime());
}
@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);
}
/**
* 日期转字符串
* @param date
* @param dateFormat
* @return
*/
public static String dateToString(Date date, String dateFormat) {
SimpleDateFormat formatter = new SimpleDateFormat(dateFormat);
return formatter.format(date);
}
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
}
/**
* 将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));
}