格式化日期并返回日期,而不是字符串 [英] Format a Date and returning a Date, not a String

查看:75
本文介绍了格式化日期并返回日期,而不是字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用以下格式"yyyy-MM-dd'T'HH:mm:ss"获取当前时间的日期

I need to get the Date of the current time with the following format "yyyy-MM-dd'T'HH:mm:ss"

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");   

我知道如何使用SimpleDateFormat格式化日期.最后,我得到一个字符串.但是我需要获取格式化的日期,而不是字符串,据我所知,我无法将字符串转换回日期,可以吗?

I know how to format a Date using SimpleDateFormat. At the end I get a String. But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?

如果我只返回日期,则它是一个日期,但格式不正确:

If I just return the Date, it is a Date but it is not properly formatted:

Timestamp ts = new Timestamp(new Date().getTime()); 

不幸的是,我需要得到结果作为日期,而不是字符串,因此我不能使用sdf.format(New Date().getTime()),因为它会返回字符串.另外,我需要返回的日期是当前时间的日期,而不是静态字符串.我希望这可以澄清

Unfortunately I need to get the outcome as a Date, not a String, so I cannot use sdf.format(New Date().getTime()) as this returns a String. Also, the Date I need to return is the Date of the current time, not from a static String. I hope that clarifies

推荐答案

但是我需要获取格式化的日期,而不是字符串,据我所知,我无法将字符串转换回日期,可以吗?

But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?

由于您知道DateTime格式,因此实际上很容易将日期格式设置为字符串,反之亦然.我个人将使用字符串到日期和日期到字符串转换方法创建一个单独的类:

Since you know the DateTime-Format, it's actually pretty easy to format from Date to String and vice-versa. I would personally make a separate class with a string-to-date and date-to-string conversion method:

public class DateConverter{

    public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    public static Date convertStringToDate(final String str){
        try{
            return DATE_FORMAT.parse(str);
        } catch(Exception ex){
            //TODO: Log exception
            return null;
        }
    }

    public static String convertDateToString(final Date date){
        try{
            return DATE_FORMAT.format(date);
        } catch(Exception ex){
            //TODO: Log exception
            return null;
        }
    }
}

用法:

// Current date-time:
Date date = new Date();

// Convert the date to a String and print it
String formattedDate = DateConverter.convertDateToString(date);
System.out.println(formattedDate);

// Somewhere else in the code we have a String date and want to convert it back into a Date-object:
Date convertedDate = DateConverter.convertStringToDate(formattedDate);

这篇关于格式化日期并返回日期,而不是字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆