【问题标题】:How to compare Google Appengine DateTime against a Date object in Java?如何将 Google Appengine DateTime 与 Java 中的 Date 对象进行比较?
【发布时间】:2015-04-07 12:57:50
【问题描述】:

我是 Google Appengine 的新手。在我的应用程序中,数据存储实体存储一个 java.util.Date 对象。我想查询数据存储以返回特定时间之前的所有实体。我的代码是:

Date date = new Date();
Query<Event> query = ofy().load().type(Event.class).order("date");
query = query.filter("date <", date);

执行时会报错:Invalid date/time format: Sat Apr 04 00:40:22 IST 2015

如果此格式无效,我需要使用哪种格式查询?

【问题讨论】:

    标签: java google-app-engine


    【解决方案1】:

    这是一个简单的代码

    import java.util.Date;
    
    import com.googlecode.objectify.annotation.Entity;
    import com.googlecode.objectify.annotation.Id;
    import com.googlecode.objectify.annotation.Index;
    
    @Entity
    public class EntityDate {
        public EntityDate() {
            // Objectify needed
        }
    
        @Id
        private Long id;
    
        @Index
        public Date date;
    }
    

    这里是进行查询的代码

    Date date = new Date();
    
    Objectify ofy = ObjectifyService.ofy();
    ObjectifyService.register(EntityDate.class);
    EntityDate entityDate = new EntityDate();
    entityDate.date = date;
    ofy.save().entities(entityDate);
    
    Query<EntityDate> ofyQuery = ofy.load().type(EntityDate.class).order("date");
    ofyQuery = ofyQuery.filter("date <", date);
    List<EntityDate> list = ofyQuery.list();
    
    Logger.getLogger("EntityDate").info(list.toString());
    

    实体已正确保存

    查询提供 4 个结果

    [EntityDate@6780874d, EntityDate@27330551, EntityDate@6a21cf2, EntityDate@7d1a5744]
    

    该类的默认toString() 有点难看,但它说明了查询正确执行。

    您能否提供Event 类的来源以及执行查询的代码的延续?

    【讨论】:

    • 我的实体类非常相似,只是一个 POJO。仍然查询对我不起作用。因此,我没有尝试使用默认日期格式进行查询,而是尝试使用 SimpleDateFormat 将其转换为不同的格式,并且成功了!不过谢谢你的帮助。
    • 您是在查询前格式化日期还是直接使用 java.util.Date 对象?
    • 其实早些时候我试图直接使用新创建的 java.util.Date 对象并得到错误。所以现在我在查询之前对其进行格式化,它工作正常。
    • 这很奇怪,我的代码直接使用 java.util.Date 可以正常工作。您使用的是哪个版本的 Objectify?
    • 很抱歉回复晚了。这只是代码的一部分。我现在使用的方法的整个代码是: SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");日期日期 = sdf.parse(fromDate); //fromDate 是提供的参数 Query query = ofy().load().type(Event.class).order("date"); query = query.filter("日期 >", 日期); return query.list();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多