Java 类org.joda.time.format.DateTimeFormatter 实例源码
项目:es-sql
文件:QueryTest.java
@Test
public void dateSearchBraces() throws IOException, SqlParseException, SQLFeatureNotSupportedException, ParseException {
DateTimeFormatter formatter = DateTimeFormat.forPattern(TS_DATE_FORMAT);
DateTime dateToCompare = new DateTime(2015, 3, 15, 0, 0, 0);
SearchHits response = query(String.format("SELECT odbc_time FROM %s/odbc WHERE odbc_time < {ts '2015-03-15 00:00:00.000'}", TEST_INDEX));
SearchHit[] hits = response.getHits();
for(SearchHit hit : hits) {
Map<String, Object> source = hit.getSource();
String insertTimeStr = (String) source.get("odbc_time");
insertTimeStr = insertTimeStr.replace("{ts '", "").replace("'}", "");
DateTime insertTime = formatter.parseDateTime(insertTimeStr);
String errorMessage = String.format("insert_time must be smaller then 2015-03-15. found: %s", insertTime);
Assert.assertTrue(errorMessage, insertTime.isBefore(dateToCompare));
}
}
项目:Artificial-Intelligent-chat-bot-
文件:IntervalUtils.java
public static int getYearsBetween(final String date1, final String date2, String format){
try {
final DateTimeFormatter fmt =
DateTimeFormat
.forPattern(format)
.withChronology(
LenientChronology.getInstance(
GregorianChronology.getInstance()));
return Years.yearsBetween(
fmt.parseDateTime(date1),
fmt.parseDateTime(date2)
).getYears();
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
项目:jwala
文件:JvmCommandFactory.java
/**
* Generate parameters for JVM Heap dump
*
* @param scriptName
* @param jvm
* @return
*/
private ExecCommand getExecCommandForHeapDump(String scriptName, Jvm jvm) {
final String trimmedJvmName = StringUtils.deleteWhitespace(jvm.getJvmName());
final String jvmRootDir = Paths.get(jvm.getTomcatMedia().getRemoteDir().toString() + '/' + trimmedJvmName + '/' +
jvm.getTomcatMedia().getRootDir()).normalize().toString();
final DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyyMMdd.HHmmss");
final String dumpFile = "heapDump." + trimmedJvmName + "." + formatter.print(DateTime.now());
final String dumpLiveStr = ApplicationProperties.getAsBoolean(PropertyKeys.JMAP_DUMP_LIVE_ENABLED.name()) ? "live," : "\"\"";
final String heapDumpDir = jvm.getTomcatMedia().getRemoteDir().normalize().toString() + "/" + jvm.getJvmName();
return new ExecCommand(getFullPathScript(jvm, scriptName), jvm.getJavaHome(), heapDumpDir, dumpFile,
dumpLiveStr , jvmRootDir, jvm.getJvmName());
}
项目:dremio-oss
文件:FragmentHandler.java
void checkStateAndLogIfNecessary() {
if (!fragmentStarted) {
final DateTimeFormatter formatter = ISODateTimeFormat.dateTime();
if (isCancelled()) {
logger.warn("Received cancel request at {} for fragment {} that was never started",
formatter.print(cancellationTime),
QueryIdHelper.getQueryIdentifier(handle));
}
FragmentEvent event;
while ((event = finishedReceivers.poll()) != null) {
logger.warn("Received early fragment termination at {} for path {} {} -> {} for a fragment that was never started",
formatter.print(event.time),
QueryIdHelper.getQueryId(handle.getQueryId()),
QueryIdHelper.getFragmentId(event.handle),
QueryIdHelper.getFragmentId(handle)
);
}
}
}
项目:webside
文件:TestJoda.java
@Test
public void testJoda()
{
DateTimeFormatter format = DateTimeFormat .forPattern("yyyy-MM-dd HH:mm:ss");
//时间解析
DateTime dateTime2 = DateTime.parse("2012-12-21 23:22:45", format);
//时间格式化,输出==> 2012/12/21 23:22:45 Fri
String string_u = dateTime2.toString("yyyy/MM/dd HH:mm:ss EE");
System.out.println(string_u);
//格式化带Locale,输出==> 2012年12月21日 23:22:45 星期五
String string_c = dateTime2.toString("yyyy年MM月dd日 HH:mm:ss EE",Locale.CHINESE);
System.out.println(string_c);
LocalDate date = LocalDate.parse("2012-12-21 23:22:45", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
Date dates = date.toDate();
System.out.println(dates);
}
项目:elasticsearch_my
文件:BaseXContentTestCase.java
public void testDate() throws Exception {
assertResult("{'date':null}", () -> builder().startObject().field("date", (Date) null).endObject());
assertResult("{'date':null}", () -> builder().startObject().field("date").value((Date) null).endObject());
final Date d1 = new DateTime(2016, 1, 1, 0, 0, DateTimeZone.UTC).toDate();
assertResult("{'d1':'2016-01-01T00:00:00.000Z'}", () -> builder().startObject().field("d1", d1).endObject());
assertResult("{'d1':'2016-01-01T00:00:00.000Z'}", () -> builder().startObject().field("d1").value(d1).endObject());
final Date d2 = new DateTime(2016, 12, 25, 7, 59, 42, 213, DateTimeZone.UTC).toDate();
assertResult("{'d2':'2016-12-25T07:59:42.213Z'}", () -> builder().startObject().field("d2", d2).endObject());
assertResult("{'d2':'2016-12-25T07:59:42.213Z'}", () -> builder().startObject().field("d2").value(d2).endObject());
final DateTimeFormatter formatter = randomFrom(ISODateTimeFormat.basicDate(), ISODateTimeFormat.dateTimeNoMillis());
final Date d3 = DateTime.now().toDate();
String expected = "{'d3':'" + formatter.print(d3.getTime()) + "'}";
assertResult(expected, () -> builder().startObject().field("d3", d3, formatter).endObject());
assertResult(expected, () -> builder().startObject().field("d3").value(d3, formatter).endObject());
expectNonNullFormatterException(() -> builder().startObject().field("d3", d3, null).endObject());
expectNonNullFormatterException(() -> builder().startObject().field("d3").value(d3, null).endObject());
expectNonNullFormatterException(() -> builder().value(null, 1L));
}
项目:sentry
文件:DayOfWeekDescriptionBuilder.java
@Override
protected String getSingleItemDescription(String expression) {
String exp = expression;
if (expression.contains("#")) {
exp = expression.substring(0, expression.indexOf("#"));
} else if (expression.contains("L")) {
exp = exp.replace("L", "");
}
if (StringUtils.isNumeric(exp)) {
int dayOfWeekNum = Integer.parseInt(exp);
boolean isZeroBasedDayOfWeek = (options == null || options.isZeroBasedDayOfWeek());
boolean isInvalidDayOfWeekForSetting = (options != null && !options.isZeroBasedDayOfWeek() && dayOfWeekNum <= 1);
if (isInvalidDayOfWeekForSetting || (isZeroBasedDayOfWeek && dayOfWeekNum == 0)) {
return DateAndTimeUtils.getDayOfWeekName(7);
} else if (options != null && !options.isZeroBasedDayOfWeek()) {
dayOfWeekNum -= 1;
}
return DateAndTimeUtils.getDayOfWeekName(dayOfWeekNum);
} else {
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("EEE").withLocale(Locale.ENGLISH);
return dateTimeFormatter.parseDateTime(WordUtils.capitalizeFully(exp)).dayOfWeek().getAsText(I18nMessages.getCurrentLocale());
}
}
项目:Artificial-Intelligent-chat-bot-
文件:IntervalUtils.java
public static int getMonthsBetween(final String date1, final String date2, String format){
try {
final DateTimeFormatter fmt =
DateTimeFormat
.forPattern(format)
.withChronology(
LenientChronology.getInstance(
GregorianChronology.getInstance()));
return Months.monthsBetween(
fmt.parseDateTime(date1),
fmt.parseDateTime(date2)
).getMonths();
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
项目:alexa-skill
文件:NewEventSpeechlet.java
private SpeechletResponse handleConfirmed(IntentRequest request, Session session)
throws CalendarWriteException {
final String dateFormat = session.getAttribute(SESSION_DATE_FORMAT).toString();
final DateTimeFormatter parser = DateTimeFormat.forPattern(dateFormat);
final String title = collectSummary(request);
final String calendar = session.getAttribute(SESSION_CALENDAR) != null ? session.getAttribute(SESSION_CALENDAR).toString() : null;
final String from = session.getAttribute(SESSION_FROM).toString();
final String to = session.getAttribute(SESSION_TO).toString();
calendarService.createEvent(calendar, title,
parser.parseDateTime(from),
parser.parseDateTime(to));
SimpleCard card = new SimpleCard();
card.setTitle(messageService.de("event.new.card.title"));
card.setContent(messageService.de("event.new.card.content", title, from, to));
session.removeAttribute(BasicSpeechlet.KEY_DIALOG_TYPE);
return SpeechletResponse.newTellResponse(
speechService.speechNewEventSaved(request.getLocale()),
card);
}
项目:logistimo-web-service
文件:ReportPluginService.java
private String getReportTableStartTime(JSONObject jsonObject, String endTime)
throws ParseException {
switch (jsonObject.getString(QueryHelper.PERIODICITY)) {
case QueryHelper.PERIODICITY_MONTH:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM");
Calendar toDate = new GregorianCalendar();
toDate.setTime(format.parse(endTime));
toDate.add(Calendar.MONTH, -1*(QueryHelper.MONTHS_LIMIT-1));
return format.format(toDate.getTime());
case QueryHelper.PERIODICITY_WEEK:
DateTimeFormatter mDateTimeFormatter = DateTimeFormat.forPattern(
QueryHelper.DATE_FORMAT_DAILY);
DateTime toTime = mDateTimeFormatter.parseDateTime(endTime);
return mDateTimeFormatter.print(toTime.minusWeeks(QueryHelper.WEEKS_LIMIT-1));
default:
mDateTimeFormatter = DateTimeFormat.forPattern(QueryHelper.DATE_FORMAT_DAILY);
toTime = mDateTimeFormatter.parseDateTime(endTime);
return mDateTimeFormatter.print(toTime.minusDays(QueryHelper.DAYS_LIMIT-1));
}
}
项目:hyperrail-for-android
文件:RouteSearchFragment.java
@Override
public void onDateTimePicked(DateTime d) {
searchDateTime = d;
DateTime now = new DateTime();
DateTimeFormatter df = DateTimeFormat.forPattern("dd MMMM yyyy");
DateTimeFormatter tf = DateTimeFormat.forPattern("HH:mm");
String day = df.print(searchDateTime);
String time = tf.print(searchDateTime);
String at = getActivity().getResources().getString(R.string.time_at);
if (now.get(DateTimeFieldType.year()) == searchDateTime.get(DateTimeFieldType.year())) {
if (now.get(DateTimeFieldType.dayOfYear()) == searchDateTime.get(DateTimeFieldType.dayOfYear())) {
day = getActivity().getResources().getString(R.string.time_today);
} else //noinspection RedundantCast
if (now.get(DateTimeFieldType.dayOfYear()) + 1 == (int) searchDateTime.get(DateTimeFieldType.dayOfYear())) {
day = getActivity().getResources().getString(R.string.time_tomorrow);
}
}
vDatetime.setText(day + " " + at + " " + time);
}
项目:flume-release-1.7.0
文件:TestBucketPath.java
@Test
public void testDateRace() {
Clock mockClock = mock(Clock.class);
DateTimeFormatter parser = ISODateTimeFormat.dateTimeParser();
long two = parser.parseMillis("2013-04-21T02:59:59-00:00");
long three = parser.parseMillis("2013-04-21T03:00:00-00:00");
when(mockClock.currentTimeMillis()).thenReturn(two, three);
// save & modify static state (yuck)
Clock origClock = BucketPath.getClock();
BucketPath.setClock(mockClock);
String pat = "%H:%M";
String escaped = BucketPath.escapeString(pat,
new HashMap<String, String>(),
TimeZone.getTimeZone("UTC"), true, Calendar.MINUTE, 10, true);
// restore static state
BucketPath.setClock(origClock);
Assert.assertEquals("Race condition detected", "02:50", escaped);
}
项目:dremio-oss
文件:TestNewDateFunctions.java
@Test
public void testUnixTimeStampForDateWithPattern() throws Exception {
DateTimeFormatter formatter = DateFunctionsUtils.getFormatterForFormatString("YYYY-MM-DD HH:MI:SS.FFF");
date = formatter.parseLocalDateTime("2009-03-20 11:30:01.0");
unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
testBuilder()
.sqlQuery("select unix_timestamp('2009-03-20 11:30:01.0', 'YYYY-MM-DD HH:MI:SS.FFF') from cp.`employee.json` limit 1")
.ordered()
.baselineColumns("EXPR$0")
.baselineValues(unixTimeStamp)
.build().run();
formatter = DateFunctionsUtils.getFormatterForFormatString("YYYY-MM-DD");
date = formatter.parseLocalDateTime("2009-03-20");
unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
testBuilder()
.sqlQuery("select unix_timestamp('2009-03-20', 'YYYY-MM-DD') from cp.`employee.json` limit 1")
.ordered()
.baselineColumns("EXPR$0")
.baselineValues(unixTimeStamp)
.build().run();
}
项目:dremio-oss
文件:TestNewDateFunctions.java
@Test
public void testIsDate2() throws Exception {
DateTimeFormatter formatter = DateFunctionsUtils.getFormatterForFormatString("YYYY-MM-DD");
testBuilder()
.sqlQuery("select case when isdate(date1) then cast(date1 as date) else null end res1 from " + dateValues)
.unOrdered()
.baselineColumns("res1")
.baselineValues(formatter.parseLocalDateTime("1900-01-01"))
.baselineValues(formatter.parseLocalDateTime("3500-01-01"))
.baselineValues(formatter.parseLocalDateTime("2000-12-31"))
.baselineValues(new Object[] {null})
.baselineValues(new Object[] {null})
.baselineValues(new Object[] {null})
.build()
.run();
}
项目:integrations
文件:FormattedDateTime.java
private void formatDate( String date, String datePattern ) {
DateTimeFormatter customDateFormatter = DateTimeFormat.forPattern( datePattern );
String dateString = date;
if ( date != null ) {
dateString = date;
// dateString should already be padded with zeros before being parsed
myDate = date == null ? null : LocalDate.parse( dateString, customDateFormatter );
dt = dt.withDate( myDate.getYear(), myDate.getMonthOfYear(), myDate.getDayOfMonth() );
}
}
项目:lams
文件:JodaTimeFormatterRegistrar.java
private DateTimeFormatter getFormatter(Type type) {
DateTimeFormatter formatter = this.formatters.get(type);
if (formatter != null) {
return formatter;
}
DateTimeFormatter fallbackFormatter = getFallbackFormatter(type);
return this.factories.get(type).createDateTimeFormatter(fallbackFormatter);
}
项目:integrations
文件:FormattedDateTime.java
private void formatDate( String date, String datePattern ) {
DateTimeFormatter customDateFormatter = DateTimeFormat.forPattern( datePattern );
String dateString = date;
if ( date != null && !myDate.equals( "" ) ) {
dateString = date;
// dateString should already be padded with zeros before being parsed
myDate = date == null ? null : LocalDate.parse( dateString, customDateFormatter );
dt = dt.withDate( myDate.getYear(), myDate.getMonthOfYear(), myDate.getDayOfMonth() );
}
}
项目:mobile-app-dev-book
文件:MediaDetailsActivity.java
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.save_media) {
switch (mediaType) {
case 1: // text
DateTime now = DateTime.now();
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
JournalEntry currentEntry = new JournalEntry();
currentEntry.setCaption(entry_caption.getText().toString());
currentEntry.setType(mediaType);
currentEntry.setLat(ALLENDALE_LAT);
currentEntry.setLng(ALLENDATE_LNG);
currentEntry.setDate(fmt.print(now));
DatabaseReference savedEntry = entriesRef.push();
savedEntry.setValue(currentEntry);
Snackbar.make(entry_caption,
"Your entry is saved",
Snackbar.LENGTH_LONG).show();
break;
case 2: // photo
uploadMedia(mediaType, "image/jpeg", "photos");
break;
case 3: // audio
uploadMedia(mediaType, "audio/m4a", "audio");
break;
case 4: // video
uploadMedia(mediaType, "video/mp4", "videos");
break;
}
return true;
}
return false;
}
项目:dremio-oss
文件:TestNewDateFunctions.java
@Test
public void testUnixTimeStampForDate() throws Exception {
DateTimeFormatter formatter = DateFunctionsUtils.getFormatterForFormatString("YYYY-MM-DD HH24:MI:SS");
date = formatter.parseLocalDateTime("2009-03-20 11:30:01");
unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
testBuilder()
.sqlQuery("select unix_timestamp('2009-03-20 11:30:01') from cp.`employee.json` limit 1")
.ordered()
.baselineColumns("EXPR$0")
.baselineValues(unixTimeStamp)
.build().run();
date = formatter.parseLocalDateTime("2014-08-09 05:15:06");
unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
testBuilder()
.sqlQuery("select unix_timestamp('2014-08-09 05:15:06') from cp.`employee.json` limit 1")
.ordered()
.baselineColumns("EXPR$0")
.baselineValues(unixTimeStamp)
.build().run();
date = formatter.parseLocalDateTime("1970-01-01 00:00:00");
unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
testBuilder()
.sqlQuery("select unix_timestamp('1970-01-01 00:00:00') from cp.`employee.json` limit 1")
.ordered()
.baselineColumns("EXPR$0")
.baselineValues(unixTimeStamp)
.build().run();
// make sure we support 24 hour notation by default
date = formatter.parseLocalDateTime("1970-01-01 23:12:12");
unixTimeStamp = com.dremio.common.util.DateTimes.toMillis(date) / 1000;
testBuilder()
.sqlQuery("select unix_timestamp('1970-01-01 23:12:12') from cp.`employee.json` limit 1")
.ordered()
.baselineColumns("EXPR$0")
.baselineValues(unixTimeStamp)
.build().run();
}
项目:es-sql
文件:QueryTest.java
@Test
public void dateSearch() throws IOException, SqlParseException, SQLFeatureNotSupportedException, ParseException {
DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_FORMAT);
DateTime dateToCompare = new DateTime(2014, 8, 18, 0, 0, 0);
SearchHits response = query(String.format("SELECT insert_time FROM %s/online WHERE insert_time < '2014-08-18'", TEST_INDEX));
SearchHit[] hits = response.getHits();
for(SearchHit hit : hits) {
Map<String, Object> source = hit.getSource();
DateTime insertTime = formatter.parseDateTime((String) source.get("insert_time"));
String errorMessage = String.format("insert_time must be smaller then 2014-08-18. found: %s", insertTime);
Assert.assertTrue(errorMessage, insertTime.isBefore(dateToCompare));
}
}
项目:tableschema-java
文件:TypeInferrer.java
public DateTime castYearmonth(String format, String value, Map<String, Object> options) throws TypeInferringException{
Pattern pattern = Pattern.compile(REGEX_YEARMONTH);
Matcher matcher = pattern.matcher(value);
if(matcher.matches()){
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM");
DateTime dt = formatter.parseDateTime(value);
return dt;
}else{
throw new TypeInferringException();
}
}
项目:tableschema-java
文件:FieldConstraintsTest.java
@Test
public void testMinimumAndMaximumDatetime(){
Map<String, Object> violatedConstraints = null;
final String DATETIME_STRING_MINIMUM = "2000-01-15T13:44:33.000Z";
final String DATETIME_STRING_MAXIMUM = "2019-01-15T13:44:33.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateTime datetimeMin = formatter.parseDateTime(DATETIME_STRING_MINIMUM);
DateTime datetimeMax = formatter.parseDateTime(DATETIME_STRING_MAXIMUM);
Map<String, Object> constraints = new HashMap();
constraints.put(Field.CONSTRAINT_KEY_MINIMUM, datetimeMin);
constraints.put(Field.CONSTRAINT_KEY_MAXIMUM, datetimeMax);
Field field = new Field("test", Field.FIELD_TYPE_DATETIME, null, null, null, constraints);
DateTime datetime2017 = formatter.parseDateTime("2017-01-15T13:44:33.000Z");
violatedConstraints = field.checkConstraintViolations(datetime2017);
Assert.assertTrue(violatedConstraints.isEmpty());
DateTime datetimeEqualMin = formatter.parseDateTime(DATETIME_STRING_MINIMUM);
violatedConstraints = field.checkConstraintViolations(datetimeEqualMin);
Assert.assertTrue(violatedConstraints.isEmpty());
DateTime datetimeEqualMax = formatter.parseDateTime(DATETIME_STRING_MAXIMUM);
violatedConstraints = field.checkConstraintViolations(datetimeEqualMax);
Assert.assertTrue(violatedConstraints.isEmpty());
DateTime datetimeLesserThanMinBy1Sec = formatter.parseDateTime("2000-01-15T13:44:32.000Z");
violatedConstraints = field.checkConstraintViolations(datetimeLesserThanMinBy1Sec);
Assert.assertTrue(violatedConstraints.containsKey(Field.CONSTRAINT_KEY_MINIMUM));
DateTime datetimeGreaterThanMaxBy1Day = formatter.parseDateTime("2019-01-16T13:44:33.000Z");
violatedConstraints = field.checkConstraintViolations(datetimeGreaterThanMaxBy1Day);
Assert.assertTrue(violatedConstraints.containsKey(Field.CONSTRAINT_KEY_MAXIMUM));
}
项目:tableschema-java
文件:FieldConstraintsTest.java
@Test
public void testEnumDatetime(){
Map<String, Object> violatedConstraints = null;
Map<String, Object> constraints = new HashMap();
List<DateTime> enumDatetimes = new ArrayList();
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
DateTime datetime1 = formatter.parseDateTime("2000-01-15T13:44:33.000Z");
enumDatetimes.add(datetime1);
DateTime datetime2 = formatter.parseDateTime("2019-01-15T13:44:33.000Z");
enumDatetimes.add(datetime2);
constraints.put(Field.CONSTRAINT_KEY_ENUM, enumDatetimes);
Field field = new Field("test", Field.FIELD_TYPE_DATETIME, null, null, null, constraints);
violatedConstraints = field.checkConstraintViolations(datetime1);
Assert.assertTrue(violatedConstraints.isEmpty());
violatedConstraints = field.checkConstraintViolations(datetime2);
Assert.assertTrue(violatedConstraints.isEmpty());
DateTime datetime3 = formatter.parseDateTime("2003-01-15T13:44:33.000Z");
violatedConstraints = field.checkConstraintViolations(datetime3);
Assert.assertTrue(violatedConstraints.containsKey(Field.CONSTRAINT_KEY_ENUM));
}
项目:MovieApp
文件:Utils.java
public static String getReleaseDate(String date) {
DateTimeFormatter formatter = forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withLocale(Locale.US);
// DateTimeFormatter formatter = forPattern("yyyy-MM-dd").withLocale(Locale.US);
LocalDate date1 = formatter.parseLocalDate(date);
DateTimeFormatter dateTimeFormatter = forPattern("dd MMM yyyy").withLocale(Locale.US);
return dateTimeFormatter.print(date1);
}
项目:dataflow-opinion-analysis
文件:IndexerPipelineUtils.java
public static DateTime parseDateString(DateTimeFormatter formatter, String s) {
DateTime result = null;
try {
result = formatter.parseDateTime(s);
} catch (Exception e) {
result = null;
}
return result;
}
项目:dataflow-opinion-analysis
文件:IndexerPipelineUtils.java
public static Long parseDateToLong(DateTimeFormatter formatter, String s) {
Long result = null;
DateTime date = parseDateString(formatter, s);
if (date != null)
result = date.getMillis();
return result;
}
项目:os
文件:BillNoUtils.java
public static void main(String[] args) throws NoSuchAlgorithmException {
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
for (int i=1; i<=1440; i++) {
System.out.println("maps.put(\"20141109-"+i+"\", \""+sr.nextInt(10)+" "+sr.nextInt(10)+" "+sr.nextInt(10)+" "+sr.nextInt(10)+" "+sr.nextInt(10)+"\");");
}
System.out.println(LocalDate.now());
Instant in = new Instant(1414508801016L);
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
formatter=formatter.withZone(DateTimeZone.forTimeZone(TimeZone.getTimeZone("GMT+8")));
in = in.plus(100);
System.out.println(in.get(DateTimeFieldType.millisOfSecond()));
System.out.println(in.toDate());
System.out.println(formatter.print(in));
System.out.println(in.getMillis());
Pattern pattern = Pattern.compile("\"phase\":\"20141018023\"(.*)\"data\":\\[\"(\\d)\",\"(\\d)\",\"(\\d)\",\"(\\d)\",\"(\\d)\"\\]\\}\\]\\}");
Matcher matcher = pattern.matcher("{\"code\":0,\"message\":\"\",\"data\":[{\"phasetype\":200,\"phase\":\"20141018023\",\"create_at\":\"2014-01-21 14:41:05\",\"time_startsale\":\"2014-10-18 01:50:00\",\"time_endsale\":\"2014-10-18 01:55:00\",\"time_endticket\":\"2014-10-18 01:55:00\",\"time_draw\":\"2014-10-18 01:56:00\",\"status\":5,\"forsale\":0,\"is_current\":0,\"result\":{\"result\":[{\"key\":\"ball\",\"data\":[\"1\",\"5\",\"0\",\"5\",\"9\"]}]},\"result_detail\":{\"resultDetail\":[{\"key\":\"prize1\",\"bet\":\"0\",\"prize\":100000},{\"key\":\"prize2\",\"bet\":\"0\",\"prize\":20000},{\"key\":\"prize3\",\"bet\":\"0\",\"prize\":200},{\"key\":\"prize4\",\"bet\":\"0\",\"prize\":20},{\"key\":\"prize5\",\"bet\":\"0\",\"prize\":1000},{\"key\":\"prize6\",\"bet\":\"0\",\"prize\":320},{\"key\":\"prize7\",\"bet\":\"0\",\"prize\":160},{\"key\":\"prize8\",\"bet\":\"0\",\"prize\":100},{\"key\":\"prize9\",\"bet\":\"0\",\"prize\":50},{\"key\":\"prize10\",\"bet\":\"0\",\"prize\":10},{\"key\":\"prize11\",\"bet\":\"0\",\"prize\":4}]},\"pool_amount\":\"\",\"sale_amount\":\"\",\"ext\":\"\",\"fc3d_sjh\":null,\"terminal_status\":2,\"fordraw\":0,\"time_startsale_fixed\":\"2014-10-18 01:47:40\",\"time_endsale_fixed\":\"2014-10-18 01:52:40\",\"time_endsale_syndicate_fixed\":\"2014-10-18 01:55:00\",\"time_endsale_upload_fixed\":\"2014-10-18 01:55:00\",\"time_draw_fixed\":\"2014-10-18 01:56:00\",\"time_startsale_correction\":140,\"time_endsale_correction\":140,\"time_endsale_syndicate_correction\":0,\"time_endsale_upload_correction\":0,\"time_draw_correction\":0,\"time_exchange\":\"2014-12-16 01:56:00\"},{\"phasetype\":\"200\",\"phase\":\"20141018024\",\"create_at\":\"2014-01-21 14:41:05\",\"time_startsale\":\"2014-10-18 01:55:00\",\"time_endsale\":\"2014-10-18 10:00:00\",\"time_endticket\":\"2014-10-18 10:00:00\",\"time_draw\":\"2014-10-18 10:01:00\",\"status\":\"2\",\"forsale\":\"1\",\"is_current\":\"1\",\"result\":null,\"result_detail\":null,\"pool_amount\":\"\",\"sale_amount\":\"\",\"ext\":\"\",\"fc3d_sjh\":null,\"terminal_status\":\"1\",\"fordraw\":\"0\",\"time_startsale_fixed\":\"2014-10-18 01:52:40\",\"time_endsale_fixed\":\"2014-10-18 09:57:40\",\"time_endsale_syndicate_fixed\":\"2014-10-18 10:00:00\",\"time_endsale_upload_fixed\":\"2014-10-18 10:00:00\",\"time_draw_fixed\":\"2014-10-18 10:01:00\",\"time_startsale_correction\":140,\"time_endsale_correction\":140,\"time_endsale_syndicate_correction\":0,\"time_endsale_upload_correction\":0,\"time_draw_correction\":0,\"time_exchange\":\"2014-12-16 10:01:00\"}],\"redirect\":\"\",\"datetime\":\"2014-10-18 04:08:45\",\"timestamp\":1413576525}");
//Pattern pattern = Pattern.compile("(.*)message(\\d\\d)(\\d)(\\d)(\\d)");
//Matcher matcher = pattern.matcher("23fawef_message12345");
//Pattern pattern = Pattern.compile("\"number\":\"(\\d) (\\d) (\\d) (\\d) (\\d)\",\"period\":\"20141017083");
//Matcher matcher = pattern.matcher("{\"latestPeriods\":[{\"number\":\"6 0 2 2 1\",\"period\":\"20141017084\"},{\"number\":\"0 8 9 1 9\",\"period\":\"20141017083\"},{\"number\":\"4 0 4 4 6\",\"period\":\"20141017082\"},{\"number\":\"4 5 8 7 7\",\"period\":\"20141017081\"},{\"number\":\"7 2 8 5 3\",\"period\":\"20141017080\"},{\"number\":\"9 7 3 8 0\",\"period\":\"20141017079\"},{\"number\":\"3 7 6 0 1\",\"period\":\"20141017078\"},{\"number\":\"9 6 4 8 5\",\"period\":\"20141017077\"},{\"number\":\"6 4 1 8 1\",\"period\":\"20141017076\"},{\"number\":\"9 5 2 8 7\",\"period\":\"20141017075\"}],\"successful\":\"true\",\"statusDesc\":\"获取数据成功\"}");
matcher.find();
for (int i=1; i<=matcher.groupCount(); i++) {
System.out.println(matcher.group(i));
}
}
项目:mobile-app-dev-book
文件:TripEditorActivity.java
@OnClick(R.id.fab)
public void FABPressed() {
Intent result = new Intent();
currentTrip.setName(jname.getText().toString());
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
currentTrip.setStartDate(fmt.print(startDate));
currentTrip.setEndDate(fmt.print(endDate));
if (coverPhotoUrl != null)
currentTrip.setCoverPhotoUrl(coverPhotoUrl);
// add more code to initialize the rest of the fields
Parcelable parcel = Parcels.wrap(currentTrip);
result.putExtra("TRIP", parcel);
setResult(RESULT_OK, result);
finish();
}
项目:SOS-The-Healthcare-Companion
文件:OverviewPresenter.java
public ArrayList<String> getGraphGlucoseDateTime() {
ArrayList<String> glucoseDatetime = new ArrayList<>();
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm");
for (int i = 0; i < glucoseGraphObjects.size(); i++) {
glucoseDatetime.add(dateTimeFormatter.print(glucoseGraphObjects.get(i).getCreated()));
}
return glucoseDatetime;
}
项目:exam
文件:RoomController.java
@Restrict(@Group({"ADMIN"}))
public Result updateExamStartingHours() {
JsonNode root = request().body().asJson();
List<Long> roomIds = new ArrayList<>();
for (JsonNode roomId : root.get("roomIds")) {
roomIds.add(roomId.asLong());
}
List<ExamRoom> rooms = Ebean.find(ExamRoom.class).where().idIn(roomIds).findList();
for (ExamRoom examRoom : rooms) {
if (examRoom == null) {
return notFound();
}
List<ExamStartingHour> previous = Ebean.find(ExamStartingHour.class)
.where().eq("room.id", examRoom.getId()).findList();
Ebean.deleteAll(previous);
JsonNode node = request().body().asJson();
DateTimeFormatter formatter = DateTimeFormat.forPattern("dd.MM.yyyy HH:mmZZ");
for (JsonNode hours : node.get("hours")) {
ExamStartingHour esh = new ExamStartingHour();
esh.setRoom(examRoom);
// Deliberately use first/second of Jan to have no DST in effect
DateTime startTime = DateTime.parse(hours.asText(), formatter).withDayOfYear(1);
esh.setStartingHour(startTime.toDate());
esh.setTimezoneOffset(DateTimeZone.forID(examRoom.getLocalTimezone()).getOffset(startTime));
esh.save();
}
asyncUpdateRemote(examRoom);
}
return ok();
}
项目:elasticsearch_my
文件:SimpleJodaTests.java
public void testUpperBound() {
MutableDateTime dateTime = new MutableDateTime(3000, 12, 31, 23, 59, 59, 999, DateTimeZone.UTC);
DateTimeFormatter formatter = ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC);
String value = "2000-01-01";
int i = formatter.parseInto(dateTime, value, 0);
assertThat(i, equalTo(value.length()));
assertThat(dateTime.toString(), equalTo("2000-01-01T23:59:59.999Z"));
}
项目:elasticsearch_my
文件:SimpleJodaTests.java
public void testIsoVsCustom() {
DateTimeFormatter formatter = ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC);
long millis = formatter.parseMillis("1970-01-01T00:00:00");
assertThat(millis, equalTo(0L));
formatter = DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss").withZone(DateTimeZone.UTC);
millis = formatter.parseMillis("1970/01/01 00:00:00");
assertThat(millis, equalTo(0L));
FormatDateTimeFormatter formatter2 = Joda.forPattern("yyyy/MM/dd HH:mm:ss");
millis = formatter2.parser().parseMillis("1970/01/01 00:00:00");
assertThat(millis, equalTo(0L));
}
项目:mobile-app-dev-book
文件:JournalViewActivity.java
private File createFileName(String prefix, String ext) throws
IOException {
DateTime now = DateTime.now();
DateTimeFormatter fmt = DateTimeFormat.forPattern
("yyyyMMdd-HHmmss");
File cacheDir = getExternalCacheDir();
File media = File.createTempFile(prefix + "-" + fmt.print(now),
ext, cacheDir);
return media;
}
项目:Android_watch_magpie
文件:MainActivity.java
@Override
public void onTimeSet(RadialTimePickerDialog radialTimePickerDialog, int hourOfDay, int minute) {
timestamp.setHourOfDay(hourOfDay);
timestamp.setMinuteOfHour(minute);
DateTimeFormatter dtf = DateTimeFormat.forPattern("kk:mm dd/MM/yyyy");
textView.setText(timestamp.toString(dtf));
}
项目:elasticsearch_my
文件:TimeZoneRoundingTests.java
/**
* Test that time zones are correctly parsed. There is a bug with
* Joda 2.9.4 (see https://github.com/JodaOrg/joda-time/issues/373)
*/
public void testsTimeZoneParsing() {
final DateTime expected = new DateTime(2016, 11, 10, 5, 37, 59, randomDateTimeZone());
// Formatter used to print and parse the sample date.
// Printing the date works but parsing it back fails
// with Joda 2.9.4
DateTimeFormatter formatter = DateTimeFormat.forPattern("YYYY-MM-dd'T'HH:mm:ss " + randomFrom("ZZZ", "[ZZZ]", "'['ZZZ']'"));
String dateTimeAsString = formatter.print(expected);
assertThat(dateTimeAsString, startsWith("2016-11-10T05:37:59 "));
DateTime parsedDateTime = formatter.parseDateTime(dateTimeAsString);
assertThat(parsedDateTime.getZone(), equalTo(expected.getZone()));
}
项目:ooso
文件:Mapper.java
public String map(BufferedReader objectBufferedReader) {
try {
Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
Map<String, Long> result = new HashMap<>();
String line;
while (((line = objectBufferedReader.readLine()) != null)) {
Record currentRecord = new Record(line);
String key = String.join(
"-",
currentRecord.getPassengerCount(),
String.valueOf(dateTimeFormatter.parseDateTime(currentRecord.getTpepPickupDatetime()).getYear()),
String.valueOf(Double.valueOf(currentRecord.getTripDistance()).intValue()));
Long count = result.get(key);
result.put(key, count == null ? 1 : count + 1);
}
return gson.toJson(result);
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
项目:QDrill
文件:DateUtility.java
public static DateTimeFormatter getDateTimeFormatter() {
if (dateTimeTZFormat == null) {
DateTimeFormatter dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd");
DateTimeParser optionalTime = DateTimeFormat.forPattern(" HH:mm:ss").getParser();
DateTimeParser optionalSec = DateTimeFormat.forPattern(".SSS").getParser();
DateTimeParser optionalZone = DateTimeFormat.forPattern(" ZZZ").getParser();
dateTimeTZFormat = new DateTimeFormatterBuilder().append(dateFormatter).appendOptional(optionalTime).appendOptional(optionalSec).appendOptional(optionalZone).toFormatter();
}
return dateTimeTZFormat;
}
项目:lams
文件:Configuration.java
/**
* Gets the date format used to string'ify SAML's {@link org.joda.time.DateTime} objects.
*
* @return date format used to string'ify date objects
*/
public static DateTimeFormatter getSAMLDateFormatter() {
if (dateFormatter == null) {
DateTimeFormatter formatter = DateTimeFormat.forPattern(defaultDateFormat);
dateFormatter = formatter.withChronology(ISOChronology.getInstanceUTC());
}
return dateFormatter;
}
项目:yum
文件:EmailService.java
@Transactional
public void sendOrderSummary(LocalDate date) {
DailyMenu dailyMenu = dailyMenuRep.findByDate(date);
if (dailyMenu != null) {
DateTimeFormatter fmt = DateTimeFormat.forPattern("dd/MM/yyyy");
DateTimeFormatter fmtFull = DateTimeFormat.forPattern("EEEE dd MMMM yyyy");
String formattedDate = date.toString(fmt);
String titleDate = date.toString(fmtFull);
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
df.setMinimumFractionDigits(2);
String currency = settingsRep.findById(1).getCurrency();
//Build data
HashMap<String, HashMap<Food, Integer>> orderByFoodType = getFoodByType(getOrderItems(dailyMenu));
// create hashmap for the placeholders of the template
Map<String, Object> model = new HashMap<>();
model.put("date", titleDate);
model.put("orderItemsByMain", orderByFoodType.get("MAIN"));
model.put("orderItemsBySalad", orderByFoodType.get("SALAD"));
model.put("orderItemsByDrink", orderByFoodType.get("DRINK"));
model.put("currency", currency);
List<DailyOrder> dailyOrders = dailyMenu.getDailyOrders();
model.put("dailyOrders", dailyOrders);
String emails = settingsRep.findById(1).getReportEmail();
if (emails != null && !emails.isEmpty()) {
ArrayList<String> emailsTo = new ArrayList<>(Arrays.asList(emails.split(";")));
for (String emailTo : emailsTo) {
sendHtmlTemplateEmail(emailTo, "[Yum] Order summary for " + formattedDate, model, "order-summary.ftlh");
}
}
}
}
项目:mobile-app-dev-book
文件:NewJournalActivity.java
@OnClick(R.id.fab)
public void FABPressed() {
Intent result = new Intent();
currentTrip.setName(jname.getText().toString());
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
currentTrip.setStartDate(fmt.print(startDate));
currentTrip.setEndDate(fmt.print(endDate));
// add more code to initialize the rest of the fields
Parcelable parcel = Parcels.wrap(currentTrip);
result.putExtra("TRIP", parcel);
setResult(RESULT_OK, result);
finish();
}