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

The following examples show how to use java.text.DateFormat#format() . 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: radar   File: CatMybatisPlugin.java    License: Apache License 2.0 6 votes vote down vote up
private String getParameterValue(Object obj) {
	String value = null;
	if (obj instanceof String) {
		value = "'" + obj.toString() + "'";
	} else if (obj instanceof Date) {
		DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
		value = "'" + formatter.format(obj) + "'";
	} else {
		if (obj != null) {
			value = obj.toString();
		} else {
			value = "";
		}

	}
	return value;
}
 
Example 2
/**
 * Constructs a MonitoredCall element.
 * 
 * @param ipcCompleteVehicle
 * @param prediction
 *            The prediction for when doing stop monitoring. When doing
 *            vehicle monitoring should be set to null.
 * @param timeFormatter
 *            For converting epoch time into a Siri time string
 */
public SiriMonitoredCall(IpcVehicleComplete ipcCompleteVehicle,
		IpcPrediction prediction, DateFormat timeFormatter) {
	stopPointRef = ipcCompleteVehicle.getNextStopId();
	// Always using value of 1 for now
	visitNumber = 1;

	// Deal with the predictions if StopMonitoring query.
	// Don't have schedule time available so can't provide it.
	if (prediction != null) {
		if (prediction.isArrival()) {
			expectedArrivalTime =
					timeFormatter.format(new Date(prediction.getPredictionTime()));
		} else {
			expectedDepartureTime =
					timeFormatter.format(new Date(prediction.getPredictionTime()));
		}
	}

	// Deal with NYC MTA extensions
	extensions = new Extensions(ipcCompleteVehicle);
}
 
Example 3
Source Project: tutorials   File: SimplePostController.java    License: MIT License 6 votes vote down vote up
@RequestMapping(value = "/users/multipart", method = RequestMethod.POST)
public String uploadFile(@RequestParam final String username, @RequestParam final String password, @RequestParam("file") final MultipartFile file) {
    if (!file.isEmpty()) {
        try {
            final DateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH.mm.ss");
            final String fileName = dateFormat.format(new Date());
            final File fileServer = new File(fileName);
            fileServer.createNewFile();
            final byte[] bytes = file.getBytes();
            final BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(fileServer));
            stream.write(bytes);
            stream.close();
            return "You successfully uploaded " + username;
        } catch (final Exception e) {
            return "You failed to upload " + e.getMessage();
        }
    } else {
        return "You failed to upload because the file was empty.";
    }
}
 
Example 4
public String getTimeAfterHeadBlockTime(int diffInMilSec) {
    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    try {
        Date date = sdf.parse( this.head_block_time);

        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add( Calendar.MILLISECOND, diffInMilSec);
        date = c.getTime();

        return sdf.format(date);

    } catch (ParseException e) {
        e.printStackTrace();
        return this.head_block_time;
    }
}
 
Example 5
/**
 * Initiates the combo-box that hold the values for the manual timestamps
 * that can be inserted when editing new entries (CNewEntry-dialog).
 */
private void initComboboxManualTimestamp() {
    // remove all items from the combobox
    jComboBoxManualTimestamp.removeAllItems();
    // iterate constant-array that holds all date-format-strings
    for (String item : Constants.manualTimestamp) {
        // create a new dateformat out of that string
        DateFormat df = new SimpleDateFormat(item);
        // and convert it to a string-item
        String timestamp = df.format(new Date());
        // add it to combobox
        jComboBoxManualTimestamp.addItem(timestamp);
    }
    // select initial value
    jComboBoxManualTimestamp.setSelectedIndex(settings.getManualTimestamp());
}
 
Example 6
@BeforeTest
public void setUpMethod() throws Exception {
	File tmpDir = new File(System.getProperty("java.io.tmpdir"));

	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
	Date date = new Date();

	tmpOutputFolder = new File(tmpDir, "BinaryInteractionFileTest_" + dateFormat.format(date));

	Runtime.getRuntime().addShutdownHook(new Thread() {
		@Override
		public void run() {
			for (File file : tmpOutputFolder.listFiles()) {
					file.delete();
			}
			tmpOutputFolder.delete();
		}
	});

	tmpOutputFolder.mkdir();


}
 
Example 7
Source Project: ormlite-core   File: DateStringTypeTest.java    License: ISC License 5 votes vote down vote up
@Test
public void testDateString() throws Exception {
	Class<LocalDateString> clazz = LocalDateString.class;
	Dao<LocalDateString, Object> dao = createDao(clazz, true);
	Date val = new Date();
	String format = "yyyy-MM-dd HH:mm:ss.SSSSSS";
	DateFormat dateFormat = new SimpleDateFormat(format);
	String valStr = dateFormat.format(val);
	String sqlVal = valStr;
	LocalDateString foo = new LocalDateString();
	foo.date = val;
	assertEquals(1, dao.create(foo));
	testType(dao, foo, clazz, val, valStr, sqlVal, sqlVal, DataType.DATE_STRING, DATE_COLUMN, false, true, true,
			false, false, false, true, false);
}
 
Example 8
Source Project: netty-4.1.22   File: CustomReporter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        final DateFormat format = DateFormat.getDateTimeInstance(
                DateFormat.SHORT, DateFormat.MEDIUM, locale);
        format.setTimeZone(timeZone);
        final String dateTime = format.format(new Date(clock.time()));
        out.print(dateTime);
        out.print(' ');
        for (int i = 0; i < CONSOLE_WIDTH - dateTime.length() - 1; i++) {
            out.print('=');
        }
        out.println();
        for (final Entry<String, SortedMap<MetricName, Metric>> entry : getMetricsRegistry()
                .groupedMetrics(predicate).entrySet()) {
            out.print(entry.getKey());
            out.println(':');
            for (final Entry<MetricName, Metric> subEntry : entry
                    .getValue().entrySet()) {
                out.print("  ");
                out.print(subEntry.getKey().getName());
                out.println(':');
                subEntry.getValue().processWith(this, subEntry.getKey(),
                        out);
                out.println();
            }
            out.println();
        }
        out.println();
        out.flush();
    } catch (final Exception e) {
        e.printStackTrace(out);
    }
}
 
Example 9
private static boolean testRequiredLocales() {
    boolean pass = true;

    TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
    Calendar calendar = Calendar.getInstance(Locale.US);
    calendar.clear();
    calendar.set(2001, 4, 10, 12, 0, 0);
    Date date = calendar.getTime();

    Locale[] available = Locale.getAvailableLocales();
    for (int i = 0; i < requiredLocales.length; i++) {
        Locale locale = requiredLocales[i];
        boolean found = false;
        for (int j = 0; j < available.length; j++) {
            if (available[j].equals(locale)) {
                found = true;
                break;
            }
        }
        if (!found) {
            System.out.println("Locale not available: " + locale);
            pass = false;
        } else {
            DateFormat format =
                    DateFormat.getDateInstance(DateFormat.FULL, locale);
            String dateString = format.format(date);
            if (!dateString.equals(requiredLocaleDates[i])) {
                System.out.println("Incorrect date string for locale "
                        + locale + ". Expected: " + requiredLocaleDates[i]
                        + ", got: " + dateString);
                pass = false;
            }
        }
    }
    return pass;
}
 
Example 10
Source Project: arcusandroid   File: TimeWindowModel.java    License: Apache License 2.0 5 votes vote down vote up
public String getStringRepresentation() {
    DateFormat sdf = new SimpleDateFormat("h:mm a", Locale.getDefault());
    Calendar startCal = getStartTimeCalendar();
    Calendar endCal   = getEndTimeCalendar();

    String startDOW = getCalendarAbbrFor(startCal.get(Calendar.DAY_OF_WEEK));
    String startTime = sdf.format(startCal.getTime());

    String endDOW = getCalendarAbbrFor(endCal.get(Calendar.DAY_OF_WEEK));
    String endTime = sdf.format(endCal.getTime());

    return String.format("%s %s - %s %s", startDOW, startTime, endDOW, endTime);
}
 
Example 11
Source Project: sofa-acts   File: DateUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String getShortFirstDayOfMonth() {
    Calendar cal = Calendar.getInstance();
    Date dt = new Date();

    cal.setTime(dt);
    cal.set(Calendar.DAY_OF_MONTH, 1);

    DateFormat df = getNewDateFormat(dtShort);

    return df.format(cal.getTime());
}
 
Example 12
/**
 * Gets the formatted time stamp with the context user's time zone and the internationalized pattern.
 * @param dateTime
 * @param patternKey i18n key of the pattern
 */
public String getFormattedDateTime(final Date dateTime, final String pattern, final Locale locale, final TimeZone timeZone)
{
  if (dateTime == null) {
    return "";
  }
  final DateFormat format = locale != null ? new SimpleDateFormat(pattern, locale) : new SimpleDateFormat(pattern);
  if (timeZone != null) {
    format.setTimeZone(PFUserContext.getTimeZone());
  }
  return format.format(dateTime);
}
 
Example 13
Source Project: amazon-mws-orders   File: MwsUtl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get a ISO 8601 formatted timestamp of now.
 * 
 * @return The time stamp.
 */
static String getFormattedTimestamp() {
    DateFormat df = dateFormatPool.getAndSet(null);
    if (df == null) {
        df = createISODateFormat();
    }
    String timestamp = df.format(new Date());
    dateFormatPool.set(df);
    return timestamp;
}
 
Example 14
public TriTyperGenotypeWriterTest() {
	
	File tmpDir = new File(System.getProperty("java.io.tmpdir"));

	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
	Date date = new Date();

	tmpOutputFolder = new File(tmpDir, "GenotypeTriTyperWriterTest_" + dateFormat.format(date));


	Runtime.getRuntime().addShutdownHook(new Thread() {
		@Override
		public void run() {
			System.out.println("Removing tmp dir and files");
			for (File file : tmpOutputFolder.listFiles()) {
				System.out.println(" - Deleting: " + file.getAbsolutePath());
				file.delete();
			}
			System.out.println(" - Deleting: " + tmpOutputFolder.getAbsolutePath());
			tmpOutputFolder.delete();
		}
	});

	tmpOutputFolder.mkdir();

	System.out.println("Temp folder with output of this test: " + tmpOutputFolder.getAbsolutePath());
	
}
 
Example 15
Source Project: util   File: Date.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 将日期转换成长日期字符串 例如:2009-09-09 01:01:01
 * @return String 
 */
public String toLongDate() {
	DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	return (null == this) ? null : df.format(this);
}
 
Example 16
Source Project: teamengine   File: ReportLog.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Creates report logs that consists of test statics by extracting information from 
 * the Test suite results. These Report logs are then printed in the TestNG HTML reports.
 * 
 * @param suite is the test suite from which you want to extract test results information.
 */
public void generateLogs(ISuite suite) {
    Reporter.clear(); // clear output from previous test runs
    Reporter.log("The result of the test is-\n\n");

    //Following code gets the suite name
    String suiteName = suite.getName();
    //Getting the results for the said suite
    Map<String, ISuiteResult> suiteResults = suite.getResults();
    String input = null;
    String result;
    String failReport = null;
    String failReportConformance2=",";
    int passedTest = 0;
    int failedTest = 0;
    int skippedTest = 0;
    int finalPassedTest=0;
    int finalSkippedTest=0;
    int finalFailedTest=0;
    int count = 0;
    String date = null;
    for (ISuiteResult sr : suiteResults.values()) {
        count++;
        ITestContext tc = sr.getTestContext();
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Calendar cal = Calendar.getInstance();
        if (count == 1) {
            date = dateFormat.format(cal.getTime());
            input = tc.getAttribute("Input").toString();
            failReport = tc.getAttribute("TestResultReport").toString();
            passedTest = tc.getPassedTests().getAllResults().size();
            skippedTest = tc.getSkippedTests().getAllResults().size();
            failedTest = tc.getFailedTests().getAllResults().size();

        } else {
            int no_of_failedTest = tc.getFailedTests().getAllResults().size();
            int no_of_skippedTest = tc.getSkippedTests().getAllResults().size();
            int no_of_passedTest = tc.getPassedTests().getAllResults().size();
            if(no_of_failedTest!=0 || no_of_passedTest !=0)
            {
                if (no_of_failedTest == 0 && no_of_passedTest !=0 ) {
                failReportConformance2 = failReportConformance2+", "+input + " conform to the clause A." + count + " of "+suiteName;
            } else {
                    failReportConformance2 = failReportConformance2+", "+input + " does not conform to the clause A." + count + " of "+suiteName;
                
            }
            finalPassedTest = finalPassedTest + no_of_passedTest;
            finalSkippedTest = finalSkippedTest + no_of_skippedTest;
            finalFailedTest = finalFailedTest + no_of_failedTest;
        }
        }

    }
    failedTest+=finalFailedTest;
    skippedTest+=finalSkippedTest;
    passedTest+=finalPassedTest;
    if(failedTest>0){
      result="Fail";
    }else{
      result="Pass";
    }
    Reporter.log("**RESULT: " + result);
    Reporter.log("**INPUT: " + input);
    Reporter.log("**TEST NAME AND VERSION    :" + suiteName);
    Reporter.log("**DATE AND TIME PERFORMED  :" + date);
    Reporter.log("Passed tests for suite '" + suiteName
            + "' is:" + passedTest);

    Reporter.log("Failed tests for suite '" + suiteName
            + "' is:"
            + failedTest);

    Reporter.log("Skipped tests for suite '" + suiteName
            + "' is:"
            + skippedTest);
    Reporter.log("\nREASON:\n\n");
    Reporter.log(failReport);
    Reporter.log(failReportConformance2);

}
 
Example 17
Source Project: sofa-acts   File: DateUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static String getWebTodayString() {
    DateFormat df = getNewDateFormat(dbSimple);

    return df.format(new Date());
}
 
Example 18
/**
 * Fonction permettant de créer un enregistrement 'émetteur' pour un export de prélèvement de
 * mensu
 *
 * @param company Une société
 * @param localDate Une date
 * @return Un enregistrement 'emetteur'
 * @throws AxelorException
 */
private String createSenderMonthlyExportCFONB(LocalDate localDate, BankDetails bankDetails)
    throws AxelorException {

  DateFormat ddmmFormat = new SimpleDateFormat("ddMM");
  String date = ddmmFormat.format(localDate.atTime(LocalTime.now()).toLocalDate());
  date += String.format("%s", StringTool.truncLeft(String.format("%s", localDate.getYear()), 1));

  // Récupération des valeurs
  String a = this.cfonbConfig.getSenderRecordCodeExportCFONB(); // Code enregistrement
  String b1 = this.cfonbConfig.getDirectDebitOperationCodeExportCFONB(); // Code opération
  String b2 = ""; // Zone réservée
  String b3 = this.cfonbConfig.getSenderNumExportCFONB(); // Numéro d'émetteur
  String c1One = ""; // Zone réservée
  String c1Two = date; // Date d'échéance
  String c2 =
      this.cfonbConfig.getSenderNameCodeExportCFONB(); // Nom/Raison sociale du donneur d'ordre
  String d1One = ""; // Référence de la remise
  String d1Two = ""; // Zone réservée
  String d2 = ""; // Zone réservée
  String d3 = bankDetails.getSortCode(); // Code guichet de la banque du donneur d'ordre
  String d4 = bankDetails.getAccountNbr(); // Numéro de compte du donneur d’ordre
  String e = ""; // Zone réservée
  String f = ""; // Zone réservée
  String g1 = bankDetails.getBankCode(); // Code établissement de la banque du donneur d'ordre
  String g2 = ""; // Zone réservée

  // Tronquage / remplissage à droite (chaine de caractère)
  b2 = StringTool.fillStringRight(b2, ' ', 8);
  b3 = StringTool.fillStringRight(b3, ' ', 6);
  c1One = StringTool.fillStringRight(c1One, ' ', 7);
  c2 = StringTool.fillStringRight(c2, ' ', 24);
  d1One = StringTool.fillStringRight(d1One, ' ', 7);
  d1Two = StringTool.fillStringRight(d1Two, ' ', 17);
  d2 = StringTool.fillStringRight(d2, ' ', 8);
  d4 = StringTool.fillStringRight(d4, ' ', 11);
  e = StringTool.fillStringRight(e, ' ', 16);
  f = StringTool.fillStringRight(f, ' ', 31);
  g2 = StringTool.fillStringRight(g2, ' ', 6);

  // Tronquage / remplissage à gauche (nombre)
  a = StringTool.fillStringLeft(a, '0', 2);
  b1 = StringTool.fillStringLeft(b1, '0', 2);
  c1Two = StringTool.fillStringLeft(c1Two, '0', 5);
  d3 = StringTool.fillStringLeft(d3, '0', 5);
  g1 = StringTool.fillStringLeft(g1, '0', 5);

  // Vérification AN / N / A
  //		cfonbToolService.testDigital(a, "");
  //		cfonbToolService.testDigital(b1, "");
  //		cfonbToolService.testDigital(d3, "");
  //		cfonbToolService.testDigital(g1, "");

  // création de l'enregistrement
  return a + b1 + b2 + b3 + c1One + c1Two + c2 + d1One + d1Two + d2 + d3 + d4 + e + f + g1 + g2;
}
 
Example 19
private String dateformatter(double timestamp) {
    Date date = new Date((long) timestamp);
    DateFormat format = DateFormat.getDateTimeInstance();
    return format.format(date);
}
 
Example 20
protected String buildFileExtensionWithDate(Date date) {
    String dateFormatStr = ".yyyy-MMM-dd.HH-mm-ss";
    DateFormat dateFormat = new SimpleDateFormat(dateFormatStr);

    return dateFormat.format(date) + GeneralLedgerConstants.BatchFileSystem.EXTENSION;


}