简体   繁体   English

java DTO中将日期类型转换为字符串格式,无需迭代

[英]java Convert Date type to String format in DTO without Iteration

I am trying to convert a date format to string format in dto class by having date type variable and string type variable which will hold string formatted fromdate variable, ie without using iteration for parsing and send it to ui as response 我正在尝试通过具有日期类型变量和字符串类型变量来将dto类中的日期格式转换为字符串格式,这些变量将保存格式为fromdate变量的字符串,即不使用迭代进行解析并将其发送给ui作为响应

private LocalDateTime date_created;
private LocalDateTime date_updated;

private String dateCreated = Utility.getStringDate(date_created);    
private String dateUpdated = Utility.getStringDate(date_updated);

While trying like above im getting Null pointer exception , it may be like data is not set in date type variable and trying to convert to string 在尝试像上述那样获取Null指针异常时,可能就像未在日期类型变量中设置数据并尝试将其转换为字符串一样

Indeed the field dateCreated were initialized once, when the date_created field still was null. 实际上,当date_created字段仍然为null时,字段dateCreated初始化了一次。

Make methods from them. 从他们那里做方法。

private String dateCreated() { return Utility.getStringDate(date_created); }
private String dateUpdated() { return Utility.getStringDate(date_updated); }

I don't know what would be wrong with formatting the date-time every time you need it formatted, need the string. 我不知道每次需要格式化日期时间时都需要格式化字符串,这是怎么回事。 But when you don't want to do that, cache the string. 但是,当您不想这样做时,请缓存字符串。 The setter for your date-time is a good place to do that, for example (not tested): 例如,您的日期时间的设置器是一个不错的选择(未经测试):

    public void setDateCreated(LocalDateTime dateCreated) {
        this.date_created = dateCreated;
        dateCreated = Utility.getStringDate(date_created);
    }

If the value may be null, you need to take that into account, of course. 当然,如果该值可能为null,则需要将其考虑在内。

Slightly more advanced, only format the string the first time you need to: 稍微高级一点,只在第一次需要时设置字符串格式:

    public String getDateCreated() {
        if (dateCreated == null && date_created != null) {
            dateCreated = Utility.getStringDate(date_created);
        }
        return dateCreated;
    }

If the date-time can be changed, you may set the string to null in the setter so that a new string will be formatted next time one is asked for. 如果可以更改日期时间,则可以在设置器中将字符串设置为null ,以便下次请求新字符串时格式化该字符串。

I did this in mongodb aggregation using $datetostring and straightway assign to string dateCreated variable "from":{ $dateToString: { format: "%Y-%m-%dT%H:%M:%S:%L"+"Z", date: "$from" } }, 我在mongodb聚合中使用$ datetostring做到了这一点,并直接分配给字符串dateCreated变量"from":{ $dateToString: { format: "%Y-%m-%dT%H:%M:%S:%L"+"Z", date: "$from" } },

where from is dto variable name dto变量名称从何而来

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM