@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));
}
}
java类org.joda.time.format.DateTimeFormat的实例源码
QueryTest.java 文件源码
项目:es-sql
阅读 21
收藏 0
点赞 0
评论 0
IntervalUtils.java 文件源码
项目:Artificial-Intelligent-chat-bot-
阅读 27
收藏 0
点赞 0
评论 0
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;
}
}
RouteDetailActivity.java 文件源码
项目:hyperrail-for-android
阅读 24
收藏 0
点赞 0
评论 0
@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);
}
DateMathIndexExpressionsIntegrationIT.java 文件源码
项目:elasticsearch_my
阅读 24
收藏 0
点赞 0
评论 0
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());
}
IndexServlet.java 文件源码
项目:dremio-oss
阅读 22
收藏 0
点赞 0
评论 0
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);
}
QuartzTest.java 文件源码
项目:webside
阅读 28
收藏 0
点赞 0
评论 0
@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);
}
DateMathExpressionResolverTests.java 文件源码
项目:elasticsearch_my
阅读 23
收藏 0
点赞 0
评论 0
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))));
}
QueryTest.java 文件源码
项目:es-sql
阅读 37
收藏 0
点赞 0
评论 0
@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);
}
}
DateTimeUtils.java 文件源码
项目:xproject
阅读 20
收藏 0
点赞 0
评论 0
/**
* <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);
}
TikaPoweredMetadataExtracter.java 文件源码
项目:alfresco-repository
阅读 20
收藏 0
点赞 0
评论 0
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();
}
DayOfWeekDescriptionBuilder.java 文件源码
项目:sentry
阅读 26
收藏 0
点赞 0
评论 0
@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());
}
}
TableNameByWindowFnTest.java 文件源码
项目:google-log-aggregation-example
阅读 22
收藏 0
点赞 0
评论 0
@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);
}
IntervalUtils.java 文件源码
项目:Artificial-Intelligent-chat-bot-
阅读 20
收藏 0
点赞 0
评论 0
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;
}
}
RestCurseProvider.java 文件源码
项目:alexa-skill
阅读 22
收藏 0
点赞 0
评论 0
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);
}
EpubCreator.java 文件源码
项目:pdf-converter
阅读 26
收藏 0
点赞 0
评论 0
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);
}
ReportPluginService.java 文件源码
项目:logistimo-web-service
阅读 27
收藏 0
点赞 0
评论 0
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));
}
}
DateFunctionsUtils.java 文件源码
项目:dremio-oss
阅读 24
收藏 0
点赞 0
评论 0
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);
}
}
NotificationLayoutBuilder.java 文件源码
项目:hyperrail-for-android
阅读 21
收藏 0
点赞 0
评论 0
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;
}
DateUtility.java 文件源码
项目:QDrill
阅读 25
收藏 0
点赞 0
评论 0
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;
}
FormattedDateTime.java 文件源码
项目:integrations
阅读 31
收藏 0
点赞 0
评论 0
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 );
}
}
GridCalendarRecyclerAdapter.java 文件源码
项目:Android-Scrapper
阅读 21
收藏 0
点赞 0
评论 0
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("");
}
}
FormattedDateTime.java 文件源码
项目:integrations
阅读 24
收藏 0
点赞 0
评论 0
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() );
}
}
MainActivity.java 文件源码
项目:Android_watch_magpie
阅读 17
收藏 0
点赞 0
评论 0
@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));
}
FormattedDateTime.java 文件源码
项目:integrations
阅读 26
收藏 0
点赞 0
评论 0
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() );
}
}
FormattedDateTime.java 文件源码
项目:integrations
阅读 20
收藏 0
点赞 0
评论 0
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 );
}
}
DateFormatterUtil.java 文件源码
项目:webside
阅读 23
收藏 0
点赞 0
评论 0
/**
* 使用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;
}
RoomController.java 文件源码
项目:exam
阅读 26
收藏 0
点赞 0
评论 0
@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();
}
TypeInferrer.java 文件源码
项目:tableschema-java
阅读 38
收藏 0
点赞 0
评论 0
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();
}
}
FieldConstraintsTest.java 文件源码
项目:tableschema-java
阅读 23
收藏 0
点赞 0
评论 0
@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));
}
Configuration.java 文件源码
项目:lams
阅读 41
收藏 0
点赞 0
评论 0
/**
* 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;
}