You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# WinForms应用中数值型字符串转日期时间的实现

日期格式转换与变量赋值方案

以下是几种主流编程语言的实现方案,可将类似72124的日期字符串转换为7/21/2024格式并赋值给字符串变量:

Python

# 从XML获取的数值型日期字符串
input_date = "72124"

# 兼容1位/2位月份的情况(如72124或122124)
if len(input_date) == 5:
    month = input_date[0]
    day = input_date[1:3]
    year = f"20{input_date[3:]}"
elif len(input_date) == 6:
    month = input_date[:2]
    day = input_date[2:4]
    year = f"20{input_date[4:]}"
else:
    raise ValueError("输入日期格式不符合预期(应为5或6位数字字符串)")

# 拼接成目标格式并赋值给变量
formatted_date = f"{month}/{day}/{year}"

# 验证结果
print(formatted_date)  # 输出:7/21/2024

Java

public class DateFormatConverter {
    public static void main(String[] args) {
        // 从XML获取的日期字符串
        String inputDate = "72124";
        String formattedDate = "";
        
        // 处理不同长度的输入
        if (inputDate.length() == 5) {
            String month = inputDate.substring(0, 1);
            String day = inputDate.substring(1, 3);
            String year = "20" + inputDate.substring(3);
            formattedDate = month + "/" + day + "/" + year;
        } else if (inputDate.length() == 6) {
            String month = inputDate.substring(0, 2);
            String day = inputDate.substring(2, 4);
            String year = "20" + inputDate.substring(4);
            formattedDate = month + "/" + day + "/" + year;
        } else {
            throw new IllegalArgumentException("输入日期格式不符合预期(应为5或6位数字字符串)");
        }
        
        // 输出结果
        System.out.println(formattedDate); // 输出:7/21/2024
    }
}

JavaScript

// 从XML获取的日期字符串
const inputDate = "72124";
let formattedDate;

// 兼容1位/2位月份的情况
if (inputDate.length === 5) {
    const month = inputDate.slice(0, 1);
    const day = inputDate.slice(1, 3);
    const year = `20${inputDate.slice(3)}`;
    formattedDate = `${month}/${day}/${year}`;
} else if (inputDate.length === 6) {
    const month = inputDate.slice(0, 2);
    const day = inputDate.slice(2, 4);
    const year = `20${inputDate.slice(4)}`;
    formattedDate = `${month}/${day}/${year}`;
} else {
    throw new Error("输入日期格式不符合预期(应为5或6位数字字符串)");
}

// 验证结果
console.log(formattedDate); // 输出:7/21/2024

内容的提问来源于stack exchange,提问作者Sarthak Mishra

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 14:05:06