要将yyyy-MM-dd hh:mm:ss格式的时间转换成yyyy-MM-dd格式,可以使用以下步骤:

  1. 将后端返回的时间字符串解析成日期对象。可以使用SimpleDateFormat类的parse()方法来实现。
String timeString = "2022-01-01 12:34:56";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = sdf.parse(timeString);
  1. 将日期对象格式化成yyyy-MM-dd格式的字符串。同样使用SimpleDateFormat类,但是这次使用"yyyy-MM-dd"作为格式模式。
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf2.format(date);

完整的代码示例:

import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) throws Exception {
        String timeString = "2022-01-01 12:34:56";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date date = sdf.parse(timeString);

        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf2.format(date);

        System.out.println(formattedDate);
    }
}

输出结果为:2022-01-0

后端返回时间是yyyy-MM-dd hhmmss格式怎么转换成yyyy-MM-dd

原文地址: https://www.cveoy.top/t/topic/iL5R 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录