将UTC日期/时间转换为本地格式。如何使用Java从Dozer Convert方法访问字段?
问题描述:
我使用Dozer框架将一个类的属性复制到另一个类。将UTC日期/时间转换为本地格式。如何使用Java从Dozer Convert方法访问字段?
public class Source {
private BigDecimal customerid;
private BigDecimal tenantid;
private BigDecimal salutation;
private String timezone;
private Calendar createdate;
}
public class Target {
private BigDecimal customerid;
private String timezone;
private String createdate;
}
到目前为止,功能已经创建并执行2号线以下时工作正常:
List<Source> customrlist = customerdao.findByTenantid(tenantid);
// copy the data into the structure that is to be returned to the client
List<Target> actual = DozerListServices.map(mapper, customrlist,
Target.class);
现在,有做出改变的愿望。
正在使用的属性之一(在Source类中)是Calendar。
目标是将“日历”转换为“字符串”(在目标类中)。该字符串在一定的格式(例如:YYYY-MM-DD)
为了做到这一点,有人建议使用“DozerConverter” - 这将看起来是这样的:
public class DozerStringToCalTimeConvert extends
DozerConverter<String, Calendar> {
public DozerStringToCalTimeConvert() {
super(String.class, Calendar.class);
}
@Override
public Calendar convertTo(String source, Calendar destination) {
if (!StringUtils.hasLength(source)) {
return null;
}
Calendar dt = null;
return dt;
}
@Override
public String convertFrom(Calendar source, String destination) {
if (source == null) {
return null;
}
return source.toString();
}
}
尽管可以使用格式化程序将日历转换为相关表示(例如:YYYY-MM-DD),但问题在于日期是UTC格式。 “源”类中的一个属性是“时区”。时区看起来像'美国/芝加哥','美国/东部'等。需要“时区”信息将UTC时间转换为当地时间。使用上面的示例Converter代码,如何更改它以便可以从Source类访问“timezone”。
TIA
答
java.time
现在的Calendar
类是传统的,由java.time类取代。
很可能您的Calendar
对象实际上是GregorianCalendar
。用instanceOf
进行测试。如果是这样,投射并转换为java.time.ZonedDateTime
。
if (myCal instanceOf GregorianCalendar) {
GregorianCalendar gc = (GregorianCalendar) myCal ;
ZonedDateTime zdt = gc.toZonedDateTime() ;
LocalDate ld = zdt.toLocalDate() ; // A date-only value deduced from the time zone assigned.
String output = ld.toString() ; // Generate string in standard ISO 8601 format YYYY-MM-DD.
}
感谢您的回复。上面,我看到你有我应该使用“ZonedDateTime”。正在使用的区域本身不是本地的,而是从数据库中获取的。在上面的“源”类中,有一个称为“时区”的区域。该值是否可以从扩展了“DozerConverter”的类访问 - 请参阅上面的转换器类“DozerStringToCalTimeConvert”。该属性可以通过“convertTo”或“convertFrom”方法访问吗?如果是这样,怎么样? –
如何在“convertTo”或“convertFrom”方法中使用“instanceOf”? TIA –
@CaseyHarrils查看我的编辑和[Oracle.com教程](https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op2.html)以了解'instanceOf'。我对Dozer一无所知,所以我无法帮助你。 –