[英]Converting UTC date/time to a local format. How would one access a field from a Dozer Convert method using Java?
我正在使用Dozer框架将一类的属性复制到另一类。
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;
}
到目前为止,已经创建了一个函数,并且在执行下面的两行时可以正常工作:
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。
目标是将“日历”转换为“字符串”(在Target类中)。 该字符串将采用某种格式(例如: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();
}
}
尽管可以使用格式化程序将Calendar转换为正确的表示形式(例如:YYYY-MM-DD),但问题在于日期采用UTC格式。 “来源”类中的属性之一是“时区”。 时区看起来像“美国/芝加哥”,“美国/东部”等。需要“时区”信息才能将UTC时间转换为本地时间。 使用上面的示例Converter代码,人们如何对其进行更改,以便可以从Source类访问“时区”。
TIA
Calendar
类现在已被遗留,由java.time类取代。
您的Calendar
对象很可能实际上是GregorianCalendar
。 用instanceOf
测试。 如果是这样,则java.time.ZonedDateTime
转换并转换为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.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.