Java 类org.joda.time.format.DateTimeFormat 实例源码
项目: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 getDaysBetween(final String date1, final String date2, String format){
try {
final DateTimeFormatter fmt =
DateTimeFormat
.forPattern(format)
.withChronology(
LenientChronology.getInstance(
GregorianChronology.getInstance()));
return Days.daysBetween(
fmt.parseDateTime(date1),
fmt.parseDateTime(date2)
).getDays();
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
项目:hyperrail-for-android
文件:RouteDetailActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
route = (Route) getIntent().getSerializableExtra("route");
this.mShowDividers = false;
super.onCreate(savedInstanceState);
setTitle(route.getDepartureStation().getLocalizedName() + " - " + route.getArrivalStation().getLocalizedName());
DateTimeFormatter df = DateTimeFormat.forPattern(getString(warning_not_realtime_datetime));
setSubTitle(df.print(route.getDepartureTime()));
// disable pull-to-refresh
// TODO: support refreshing
this.vRefreshLayout.setEnabled(false);
this.vWarningNotRealtime.setVisibility(View.GONE);
}
项目:elasticsearch_my
文件:DateMathIndexExpressionsIntegrationIT.java
public void testCreateIndexWithDateMathExpression() throws Exception {
DateTime now = new DateTime(DateTimeZone.UTC);
String index1 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now);
String index2 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(1));
String index3 = ".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.minusDays(2));
String dateMathExp1 = "<.marvel-{now/d}>";
String dateMathExp2 = "<.marvel-{now/d-1d}>";
String dateMathExp3 = "<.marvel-{now/d-2d}>";
createIndex(dateMathExp1, dateMathExp2, dateMathExp3);
GetSettingsResponse getSettingsResponse = client().admin().indices().prepareGetSettings(index1, index2, index3).get();
assertEquals(dateMathExp1, getSettingsResponse.getSetting(index1, IndexMetaData.SETTING_INDEX_PROVIDED_NAME));
assertEquals(dateMathExp2, getSettingsResponse.getSetting(index2, IndexMetaData.SETTING_INDEX_PROVIDED_NAME));
assertEquals(dateMathExp3, getSettingsResponse.getSetting(index3, IndexMetaData.SETTING_INDEX_PROVIDED_NAME));
ClusterState clusterState = client().admin().cluster().prepareState().get().getState();
assertThat(clusterState.metaData().index(index1), notNullValue());
assertThat(clusterState.metaData().index(index2), notNullValue());
assertThat(clusterState.metaData().index(index3), notNullValue());
}
项目:dremio-oss
文件:IndexServlet.java
private VersionInfo getVersionInfo() {
String version = DremioVersionInfo.getVersion(); // get dremio version (x.y.z)
long buildTime = 0;
CommitInfo commitInfo = null;
try {
URL u = Resources.getResource("git.properties");
if (u != null) {
Properties p = new Properties();
p.load(Resources.asByteSource(u).openStream());
buildTime = DateTime.parse(p.getProperty("git.build.time"), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")).getMillis();
commitInfo = new CommitInfo(
p.getProperty("git.commit.id"),
p.getProperty("git.build.user.email"),
DateTime.parse(p.getProperty("git.commit.time"), DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")).getMillis(),
p.getProperty("git.commit.message.short"));
}
} catch (Exception e) {
logger.warn("Failure when trying to access and parse git.properties.", e);
}
return new VersionInfo(version, buildTime, commitInfo);
}
项目:webside
文件:QuartzTest.java
@Test
public void testAddJob()
{
ScheduleJobEntity job = new ScheduleJobEntity();
job.setJobName("test");
job.setJobGroup("test");
job.setCronExpression("*/5 * * * * ?");
job.setJobClassName("com.webside.quartz.job.EmailJob");
//java 8 实现方式
//LocalDate localDate = LocalDate.parse("2016-07-16 15:23:43",DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//Date date = Date.from(localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
//joda实现方式
LocalDate localDate = LocalDate.parse("2016-07-16 15:23:43", DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
Date date = localDate.toDate();
job.setStartDate(date);
job.setEndDate(localDate.plusDays(10).toDate());
scheduleJobService.addJob(job);
}
项目:elasticsearch_my
文件:DateMathExpressionResolverTests.java
public void testExpression_CustomTimeZoneInIndexName() throws Exception {
DateTimeZone timeZone;
int hoursOffset;
int minutesOffset = 0;
if (randomBoolean()) {
hoursOffset = randomIntBetween(-12, 14);
timeZone = DateTimeZone.forOffsetHours(hoursOffset);
} else {
hoursOffset = randomIntBetween(-11, 13);
minutesOffset = randomIntBetween(0, 59);
timeZone = DateTimeZone.forOffsetHoursMinutes(hoursOffset, minutesOffset);
}
DateTime now;
if (hoursOffset >= 0) {
// rounding to next day 00:00
now = DateTime.now(UTC).plusHours(hoursOffset).plusMinutes(minutesOffset).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
} else {
// rounding to today 00:00
now = DateTime.now(UTC).withHourOfDay(0).withMinuteOfHour(0).withSecondOfMinute(0);
}
Context context = new Context(this.context.getState(), this.context.getOptions(), now.getMillis());
List<String> results = expressionResolver.resolve(context, Arrays.asList("<.marvel-{now/d{YYYY.MM.dd|" + timeZone.getID() + "}}>"));
assertThat(results.size(), equalTo(1));
logger.info("timezone: [{}], now [{}], name: [{}]", timeZone, now, results.get(0));
assertThat(results.get(0), equalTo(".marvel-" + DateTimeFormat.forPattern("YYYY.MM.dd").print(now.withZone(timeZone))));
}
项目:es-sql
文件:QueryTest.java
@Test
public void dateBetweenSearch() throws IOException, SqlParseException, SQLFeatureNotSupportedException {
DateTimeFormatter formatter = DateTimeFormat.forPattern(DATE_FORMAT);
DateTime dateLimit1 = new DateTime(2014, 8, 18, 0, 0, 0);
DateTime dateLimit2 = new DateTime(2014, 8, 21, 0, 0, 0);
SearchHits response = query(String.format("SELECT insert_time FROM %s/online WHERE insert_time BETWEEN '2014-08-18' AND '2014-08-21' LIMIT 3", 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"));
boolean isBetween =
(insertTime.isAfter(dateLimit1) || insertTime.isEqual(dateLimit1)) &&
(insertTime.isBefore(dateLimit2) || insertTime.isEqual(dateLimit2));
Assert.assertTrue("insert_time must be between 2014-08-18 and 2014-08-21", isBetween);
}
}
项目:xproject
文件:DateTimeUtils.java
/**
* <p>将字符串格式的日期转换为@{org.joda.time.DateTime}</p>
*
* @param dateTimeText - 日期字符串形式的值
* @param pattern - 针对dateTimeText的日期格式
* @return
*/
public static DateTime parse2DateTime(String dateTimeText, String pattern){
Assert.hasText(dateTimeText, "Parameter 'dateTimeText' can not be empty!");
Assert.hasText(dateTimeText, "Parameter 'pattern' can not be empty!");
String format = pattern;
String text = dateTimeText;
Matcher matcher = null;
String suffix = ".SSS";
//dateTimeText以毫秒结尾 && 格式pattern中没有以.SSS结尾
if((matcher = TIMESTAMP_MSEC_REGEX_PATTERN.matcher(dateTimeText)).find() && matcher.end() == dateTimeText.length() && !pattern.endsWith(suffix)){
format = format + suffix;
//dateTimeText没有以毫秒结尾 && 格式pattern中以.SSS结尾
}else if((matcher = TIMESTAMP_REGEX_PATTERN.matcher(dateTimeText)).find() && matcher.end() == dateTimeText.length() && pattern.endsWith(suffix)){
text = text + ".0";
}
return DateTimeFormat.forPattern(format).parseDateTime(text);
}
项目:alfresco-repository
文件:TikaPoweredMetadataExtracter.java
public TikaPoweredMetadataExtracter(String extractorContext, HashSet<String> supportedMimeTypes, HashSet<String> supportedEmbedMimeTypes)
{
super(supportedMimeTypes, supportedEmbedMimeTypes);
this.extractorContext = extractorContext;
// TODO Once TIKA-451 is fixed this list will get nicer
DateTimeParser[] parsersUTC = {
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ").getParser()
};
DateTimeParser[] parsers = {
DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd").getParser(),
DateTimeFormat.forPattern("yyyy/MM/dd HH:mm:ss").getParser(),
DateTimeFormat.forPattern("yyyy/MM/dd").getParser(),
DateTimeFormat.forPattern("EEE MMM dd hh:mm:ss zzz yyyy").getParser()
};
this.tikaUTCDateFormater = new DateTimeFormatterBuilder().append(null, parsersUTC).toFormatter().withZone(DateTimeZone.UTC);
this.tikaDateFormater = new DateTimeFormatterBuilder().append(null, parsers).toFormatter();
}
项目: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());
}
}
项目:google-log-aggregation-example
文件:TableNameByWindowFnTest.java
@Test
public void testApply() {
DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
Instant start = format.parseDateTime("2017-01-01 00:00:00").toInstant();
Instant end = format.parseDateTime("2017-01-01 00:01:00").toInstant();
IntervalWindow window = new IntervalWindow(start, end);
String projectId = "testProject_id";
String datasetId = "testDatasetId";
String tablePrefix = "testTablePrefix";
TableNameByWindowFn fn = new TableNameByWindowFn(projectId, datasetId, tablePrefix);
String result = fn.apply(window);
String expected = new Formatter()
.format("%s:%s.%s_%s", projectId, datasetId, tablePrefix, "20170101")
.toString();
assertEquals(expected, result);
}
项目:Artificial-Intelligent-chat-bot-
文件:IntervalUtils.java
public static int getHoursBetween(final String date1, final String date2, String format){
try {
final DateTimeFormatter fmt =
DateTimeFormat
.forPattern(format)
.withChronology(
LenientChronology.getInstance(
GregorianChronology.getInstance()));
return Hours.hoursBetween(
fmt.parseDateTime(date1),
fmt.parseDateTime(date2)
).getHours();
} catch (Exception ex) {
ex.printStackTrace();
return 0;
}
}
项目:alexa-skill
文件:RestCurseProvider.java
private BitcoinCurse convert(Response raw) {
final Double coin = 1d;
Double euro = 0d;
Matcher matcher = MONEY_PATTERN.matcher(raw.price_eur);
if(matcher.find()) {
final String rawEuro = matcher.group(1)
.replace(".", ";")
.replace(",", ".")
.replace(";", "");
euro = Double.parseDouble(rawEuro);
}
final DateTime date = DateTimeFormat.forPattern("dd.MM.yy HH:mm").parseDateTime(raw.date_de);
return new BitcoinCurse(date, coin, euro);
}
项目:pdf-converter
文件:EpubCreator.java
public void create(String title, File imgsDir, File output) throws IOException {
timestamp = DateTimeFormat.forPattern("yyyy-MM-dd'T'hh:mm:ssSZZ").print(DateTime.now());
uuid = UUID.randomUUID().toString();
this.title = title;
this.imgsDir = imgsDir;
try {
basedir = File.createTempFile(uuid,"");
basedir.delete();
basedir.mkdirs();
} catch (IOException e) {
e.printStackTrace();
}
classLoader = getClass().getClassLoader();
copyImages();
copyStandardFilez();
createOPFFile();
createIndex();
createTitlePage();
createTOC();
pack(basedir.getAbsolutePath(), output.getAbsolutePath());
FileUtils.deleteDirectory(basedir);
}
项目: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));
}
}
项目:dremio-oss
文件:DateFunctionsUtils.java
public static DateTimeFormatter getFormatterForFormatString(final String formatString) {
String jodaString = null;
try {
jodaString = JodaDateValidator.toJodaFormat(formatString);
} catch (ParseException e) {
throw UserException.functionError(e)
.message("Failure parsing the formatting string at column %d of: %s", e.getErrorOffset(), formatString)
.addContext("Details", e.getMessage())
.addContext("Format String", formatString)
.addContext("Error Offset", e.getErrorOffset())
.build(logger);
}
try {
return DateTimeFormat.forPattern(jodaString).withZoneUTC();
} catch (IllegalArgumentException ex) {
throw UserException.functionError(ex)
.message("Invalid formatting string")
.addContext("Details", ex.getMessage())
.addContext("Format String", formatString)
.build(logger);
}
}
项目:hyperrail-for-android
文件:NotificationLayoutBuilder.java
public static RemoteViews createNotificationLayout(Context context, TrainStop stop) {
DateTimeFormatter df = DateTimeFormat.forPattern("HH:mm");
RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.notif_h64);
contentView.setTextViewText(R.id.text_time1, df.print(stop.getDepartureTime()));
contentView.setTextViewText(R.id.text_delay1, String.valueOf(stop.getDepartureDelay().getStandardMinutes()));
contentView.setTextViewText(R.id.text_time2, df.print(stop.getArrivalTime()));
contentView.setViewVisibility(R.id.text_time2, View.VISIBLE);
contentView.setTextViewText(R.id.text_delay2, String.valueOf(stop.getArrivalDelay().getStandardMinutes()));
contentView.setViewVisibility(R.id.text_delay2, View.VISIBLE);
contentView.setTextViewText(R.id.text_station, stop.getStation().getLocalizedName());
contentView.setViewVisibility(R.id.text_station, View.VISIBLE);
contentView.setTextViewText(R.id.text_platform, stop.getPlatform());
contentView.setViewVisibility(R.id.layout_platform_container, View.VISIBLE);
return contentView;
}
项目:QDrill
文件:DateUtility.java
public static DateTimeFormatter getTimeFormatter() {
if (timeFormat == null) {
DateTimeFormatter timeFormatter = DateTimeFormat.forPattern("HH:mm:ss");
DateTimeParser optionalSec = DateTimeFormat.forPattern(".SSS").getParser();
timeFormat = new DateTimeFormatterBuilder().append(timeFormatter).appendOptional(optionalSec).toFormatter();
}
return timeFormat;
}
项目:integrations
文件:FormattedDateTime.java
private void formatTime( String time, String timePattern ) {
DateTimeFormatter customTimeFormatter = DateTimeFormat.forPattern( timePattern );
String timeString = time;
if ( time != null ) {
timeString = time;
// timeString should already be padded with zeros before being parsed
myTime = time == null ? null : LocalTime.parse( timeString, customTimeFormatter );
dt = dt.withTime( myTime.getHourOfDay(), myTime.getMinuteOfHour(), 0, 0 );
}
}
项目:Android-Scrapper
文件:GridCalendarRecyclerAdapter.java
private void setTexts(Game game) {
leagueName.setText(
game.getLeagueType().getAcronym() + " - " + game.getLeagueType().getScoreType());
gameFound.setVisibility(StringUtils.isNull(game.getGameUrl()) ? View.INVISIBLE : View.VISIBLE);
dateTime.setText(
DateTimeFormat.forPattern("MMM dd hh:mm aa").print(new DateTime(game.getGameDateTime(), Constants.DATE.VEGAS_TIME_ZONE).toDateTime(DateTimeZone.getDefault())));
if (game.getFirstTeam().getName().equals(DefaultFactory.Team.NAME)) {
firstTeamTitle.setText(game.getFirstTeam().getCity());
firstTeamSubtitle.setText("-");
} else {
firstTeamTitle.setText(game.getFirstTeam().getName() + " " + String.valueOf(game.getFirstTeamScore()));
firstTeamSubtitle.setText(game.getFirstTeam().getCity());
}
if (game.getSecondTeam().getName().equals(DefaultFactory.Team.NAME)) {
secondTeamTitle.setText(game.getSecondTeam().getCity());
secondTeamSubtitle.setText("-");
} else {
secondTeamTitle.setText(game.getSecondTeam().getName() + " " + String.valueOf(game.getSecondTeamScore()));
secondTeamSubtitle.setText(game.getSecondTeam().getCity());
}
bidAmount.setText(mContext.getString(R.string.bid_amount,
game.getLeagueType() instanceof Soccer_Spread ? "(" + (int) game.getVIBid().getVigAmount() + ") " : game.getVIBid().getCondition().getValue().replace("spread", ""),
String.valueOf(game.getVIBid().getBidAmount())));
if (game.getGroup() != -1) {
numberText.setText(String.valueOf(game.getGroup()));
} else {
numberText.setText("");
}
}
项目: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() );
}
}
项目: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));
}
项目: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() );
}
}
项目:integrations
文件:FormattedDateTime.java
private void formatTime( String time, String timePattern ) {
DateTimeFormatter customTimeFormatter = DateTimeFormat.forPattern( timePattern );
String timeString = time;
if ( time != null ) {
timeString = time;
// timeString should already be padded with zeros before being parsed
myTime = time == null ? null : LocalTime.parse( timeString, customTimeFormatter );
dt = dt.withTime( myTime.getHourOfDay(), myTime.getMinuteOfHour(), 0, 0 );
}
}
项目:webside
文件:DateFormatterUtil.java
/**
* 使用joda替代jdk自带的日期格式化类,因为 DateFormat 和 SimpleDateFormat 类不都是线程安全的
* 确保不会在多线程状态下使用同一个 DateFormat 或者 SimpleDateFormat 实例
* 如果多线程情况下需要访问同一个实例,那么请用同步方法
* 可以使用 joda-time 日期时间处理库来避免这些问题,如果使用java 8, 请切换到 java.time包
* 你也可以使用 commons-lang 包中的 FastDateFormat 工具类
* 另外你也可以使用 ThreadLocal 来处理这个问题
*/
@Override
public Date parse(String text, Locale locale) throws ParseException {
Date date = null;
LocalDate localDate = null;
try {
localDate = LocalDate.parse(text, DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"));
date = localDate.toDate();
} catch (Exception e) {
localDate = LocalDate.parse(text, DateTimeFormat.forPattern("yyyy-MM-dd"));
date = localDate.toDate();
throw e;
}
return date;
}
项目: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();
}
项目: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 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));
}
项目: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;
}
项目:Android-Scrapper
文件:GridDialogCalendarAdapter.java
public View getTabView(int position) {
// Given you have a custom layout in `res/layout/custom_tab.xml` with a TextView and ImageView
@SuppressLint("InflateParams") View view = LayoutInflater.from(mContext).inflate(R.layout.grd_calendar_dialog_item, null);
ButterKnife.bind(this, view);
long currentDate = 0;
for (Map.Entry<Integer, Long> entry : countMapping.entrySet()) {
if (entry.getKey() == position) {
currentDate = entry.getValue();
}
}
dateText.setText(DateTimeFormat.forPattern("MMM dd\nEEE").print(new DateTime(currentDate)));
return view;
}
项目: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;
}
项目: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));
}
}
项目:CodeWatch
文件:CustomMarkerView.java
/**
* Constructor. Sets up the MarkerView with a custom layout resource.
*
* @param context this is needed to fetch string resources.
* @param layoutResource the layout resource to use for the MarkerView.
* @param referenceTime additive value to each data value.
*/
public CustomMarkerView(Context context, int layoutResource, long referenceTime) {
super(context, layoutResource);
this.context = context;
textView = (TextView) findViewById(R.id.marker_text);
dateFormat = DateTimeFormat.forPattern("d MMM");
date = new DateTime(referenceTime);
}
项目: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;
}
项目:lams
文件:DateTimeFormatterFactory.java
/**
* Create a new {@code DateTimeFormatter} using this factory.
* <p>If no specific pattern or style has been defined,
* the supplied {@code fallbackFormatter} will be used.
* @param fallbackFormatter the fall-back formatter to use when no specific
* factory properties have been set (can be {@code null}).
* @return a new date time formatter
*/
public DateTimeFormatter createDateTimeFormatter(DateTimeFormatter fallbackFormatter) {
DateTimeFormatter dateTimeFormatter = null;
if (StringUtils.hasLength(this.pattern)) {
dateTimeFormatter = DateTimeFormat.forPattern(this.pattern);
}
else if (this.iso != null && this.iso != ISO.NONE) {
switch (this.iso) {
case DATE:
dateTimeFormatter = ISODateTimeFormat.date();
break;
case TIME:
dateTimeFormatter = ISODateTimeFormat.time();
break;
case DATE_TIME:
dateTimeFormatter = ISODateTimeFormat.dateTime();
break;
case NONE:
/* no-op */
break;
default:
throw new IllegalStateException("Unsupported ISO format: " + this.iso);
}
}
else if (StringUtils.hasLength(this.style)) {
dateTimeFormatter = DateTimeFormat.forStyle(this.style);
}
if (dateTimeFormatter != null && this.timeZone != null) {
dateTimeFormatter = dateTimeFormatter.withZone(DateTimeZone.forTimeZone(this.timeZone));
}
return (dateTimeFormatter != null ? dateTimeFormatter : fallbackFormatter);
}
项目:Android-Scrapper
文件:DashAdapter.java
private void setTexts(Game game) {
leagueName.setText(
game.getLeagueType().getAcronym() + " - " + game.getLeagueType().getScoreType());
gameFound.setVisibility(StringUtils.isNull(game.getGameUrl()) ? View.INVISIBLE : View.VISIBLE);
dateTime.setText(
DateTimeFormat.forPattern("MMM dd hh:mm aa").print(new DateTime(game.getGameDateTime(), Constants.DATE.VEGAS_TIME_ZONE).toDateTime(DateTimeZone.getDefault())));
if (game.getFirstTeam().getName().equals(DefaultFactory.Team.NAME)) {
firstTeamTitle.setText(game.getFirstTeam().getCity());
firstTeamSubtitle.setText("-");
} else {
firstTeamTitle.setText(game.getFirstTeam().getName() + " " + String.valueOf(game.getFirstTeamScore()));
firstTeamSubtitle.setText(game.getFirstTeam().getCity());
}
if (game.getSecondTeam().getName().equals(DefaultFactory.Team.NAME)) {
secondTeamTitle.setText(game.getSecondTeam().getCity());
secondTeamSubtitle.setText("-");
} else {
secondTeamTitle.setText(game.getSecondTeam().getName() + " " + String.valueOf(game.getSecondTeamScore()));
secondTeamSubtitle.setText(game.getSecondTeam().getCity());
}
bidAmount.setText(mContext.getString(R.string.bid_amount,
game.getLeagueType() instanceof Soccer_Spread ? "(" + (int) game.getVIBid().getVigAmount() + ") " : game.getVIBid().getCondition().getValue().replace("spread", ""),
String.valueOf(game.getVIBid().getBidAmount())));
if (game.getGroup() != -1) {
numberText.setText(String.valueOf(game.getGroup()));
} else {
numberText.setText("");
}
}
项目:adstxtwebcrawler
文件:AdsTxtRecord.java
@Override
public String toString() {
return DateTimeFormat.forPattern("YYYY-M-dd HH:MM:SS").print(this.getInsertDate()) + "," +
this.getSourceDomain() + "," +
this.getAdServingDomain() + "," +
this.getPublisherAccId() + "," +
this.getAccType() + "," +
this.getCertAuthId() + "\n";
}
项目:elasticsearch_my
文件:DateFieldMapperTests.java
/**
* Test that time zones are correctly parsed by the {@link DateFieldMapper}.
* There is a known bug with Joda 2.9.4 reported in https://github.com/JodaOrg/joda-time/issues/373.
*/
public void testTimeZoneParsing() throws Exception {
final String timeZonePattern = "yyyy-MM-dd" + randomFrom("ZZZ", "[ZZZ]", "'['ZZZ']'");
String mapping = XContentFactory.jsonBuilder().startObject()
.startObject("type")
.startObject("properties")
.startObject("field")
.field("type", "date")
.field("format", timeZonePattern)
.endObject()
.endObject()
.endObject().endObject().string();
DocumentMapper mapper = parser.parse("type", new CompressedXContent(mapping));
assertEquals(mapping, mapper.mappingSource().toString());
final DateTimeZone randomTimeZone = randomBoolean() ? DateTimeZone.forID(randomFrom("UTC", "CET")) : randomDateTimeZone();
final DateTime randomDate = new DateTime(2016, 03, 11, 0, 0, 0, randomTimeZone);
ParsedDocument doc = mapper.parse("test", "type", "1", XContentFactory.jsonBuilder()
.startObject()
.field("field", DateTimeFormat.forPattern(timeZonePattern).print(randomDate))
.endObject()
.bytes());
IndexableField[] fields = doc.rootDoc().getFields("field");
assertEquals(2, fields.length);
assertEquals(randomDate.withZone(DateTimeZone.UTC).getMillis(), fields[0].numericValue().longValue());
}
项目:elasticsearch_my
文件:SimpleJodaTests.java
public void testMultiParsers() {
DateTimeFormatterBuilder builder = new DateTimeFormatterBuilder();
DateTimeParser[] parsers = new DateTimeParser[3];
parsers[0] = DateTimeFormat.forPattern("MM/dd/yyyy").withZone(DateTimeZone.UTC).getParser();
parsers[1] = DateTimeFormat.forPattern("MM-dd-yyyy").withZone(DateTimeZone.UTC).getParser();
parsers[2] = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").withZone(DateTimeZone.UTC).getParser();
builder.append(DateTimeFormat.forPattern("MM/dd/yyyy").withZone(DateTimeZone.UTC).getPrinter(), parsers);
DateTimeFormatter formatter = builder.toFormatter();
formatter.parseMillis("2009-11-15 14:12:12");
}