繁体   English   中英

如何获取特定的 java.sql.Date 仅格式

[英]How to Get java.sql.Date in particular Format only

有一个问题,我必须将一种日期格式转换为另一种日期格式,并且必须以特定格式返回 java.sql.Date。

我的输入格式为 MM/dd/yyyy,输出格式应为 dd-MM-yy ..但无法获取

    DateFormat orgFormat = new SimpleDateFormat("MM/dd/yyyy");
    DateFormat targetFormat = new SimpleDateFormat("dd-MM-yy");
    
    try {
        java.util.Date inputDate = orgFormat.parse("01/01/2020");
        String formattedDate = targetFormat.format(inputDate);
        java.util.Date outputDate = targetFormat.parse(formattedDate);
        
        java.sql.Date sqlDate = new Date(outputDate.getTime());
        
        System.out.println(" Sql Date "+sqlDate);
        
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

OutPut: Sql Date 2020-01-01 // 我们需要它为01-01-20

Sql Date 只保存时间戳, 2020-01-01的时间戳与01-01-20相同。

如果您只想打印为01-01-20 ,请将您的 sout 修改为

System.out.println(" Sql Date "+ targetFormat.format(sqlDate));

如果你真的需要一个类,你可以尝试编写一个扩展java.sql.Date并覆盖toString方法的类。

例如,

public class DateV2 extends java.sql.Date {
    public DateV2(int year, int month, int day) {
        super(year, month, day);
    }

    @Override
    public String toString() {
        DateFormat targetFormat = new SimpleDateFormat("dd-MM-yy");
        return targetFormat.format(this);
    }
}

并使用DateV2替换代码中的java.sql.Date

什么System.out.println(" Sql Date "+sqlDate); sqlDate是在sqlDate上调用toString() ,如果您检查它的实现,您将看到它以yyyy-MM-dd格式返回日期。 您可以在显示日期时覆盖toString方法或使用格式化程序

System.out.println(" Sql Date " + targetFormat.format(sqlDate));`

暂无
暂无

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

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