JodaTime - how to get current time in UTC

前端 未结 7 588
天命终不由人
天命终不由人 2020-12-14 01:12

I want to get the current time in UTC. What I do so far is following (just for testing purposes):

    DateTime dt = new DateTime();
    DateTimeZone tz = Dat         


        
7条回答
  •  余生分开走
    2020-12-14 01:58

    I fixed this with this converter

    public class DateTimeConverter implements AttributeConverter {
        @Override
        public Date convertToDatabaseColumn(DateTime attribute) {
            return attribute == null ? null
                    : new Date(attribute
                            .withZone(DateTimeZone.UTC)
                            .withZoneRetainFields(DateTimeZone.getDefault())
                            .getMillis());
        }
    
        @Override
        public DateTime convertToEntityAttribute(Date dbData) {
            return dbData == null ? null
                   : new DateTime(dbData.getTime())
                            .withZoneRetainFields(DateTimeZone.UTC)
                            .withZone(DateTimeZone.getDefault());
        }
    }
    

    Dates are stored as UTC and recovered with your current time zone

提交回复
热议问题