如何在 android 中将 db2 日期转换为 YYYYMMDD

How to convert db2 date to YYYMMDD in android

我在手机上收到一个 db2 日期 1200703 作为响应。我需要将该日期转换为可读格式,如 YYYYMMDD。我怎样才能从 android 方面做到这一点?

这不是 db2 日期格式,而是某些系统存储日期的方式。这就是所谓的 CYYMMDD 整数格式。

年 = 1900 + 100*C + YY
月 = 月
日 = DD

日期字符串 1200703 采用 CYYMMDD 格式。这种格式(我不确定它是否仍在使用,因为我最后一次使用 DB2 是在 2008 年)由 DB2 使用。

为了计算年份,您需要使用以下公式:

Year = 100 * C + 1900 + YY 例如对于 CYY = 120year = 100 * 1 + 1900 + 20 = 2020.

的值

CYY 部分转换为 yyyy 格式后,您可以使用 date-time 格式化 API,如下所示:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class Main {
    public static void main(String args[]) {
        // Given date string
        String dateStr = "1200703";

        // Convert the given date string into yyyyMMdd format
        int c = Integer.parseInt(dateStr.substring(0, 1));
        int yy = Integer.parseInt(dateStr.substring(1, 3));
        int year = 100 * c + 1900 + yy;
        String dateStrConverted = String.valueOf(year) + dateStr.substring(3);

        // ########## For Java 8 onwards ##############

        // Define a formatter
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");
        LocalDate localDate = LocalDate.parse(dateStrConverted, dtf);
        System.out.println("Default format: " + localDate);

        // Printing the date in a sample custom format
        DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("EEE MMM dd yyyy");
        String strDate1 = dtf1.format(localDate);
        System.out.println(strDate1);

        // ############################################

        // ############## Before Java 8 ###############

        // Define a formatter
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        Date utilDate = null;
        try {
            utilDate = sdf.parse(dateStrConverted);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        System.out.println("Default format: " + utilDate);

        // Printing the date in a sample custom format
        SimpleDateFormat sdf1 = new SimpleDateFormat("EEE MMM dd yyyy");
        String strDate2 = sdf1.format(utilDate);
        System.out.println(strDate2);

        // ############################################
    }
}

输出:

Default format: 2020-07-03
Fri Jul 03 2020
Default format: Fri Jul 03 00:00:00 BST 2020
Fri Jul 03 2020

注:我推荐你使用the modern date-time API. If the Android version which you are using is not compatible with Java-8, I suggest you backport using 库。但是,如果您想使用旧版 API,您可以按照答案中的说明进行操作。