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

Java日期格式转换异常:YYYYMMDD转dd-mm-yyyy出错求助

Hey, let's break down why you're getting that weird 01-49-1970 output and how to fix it.

Why This Happens

You've got two key mistakes here:

  1. Treating the YYYYMMDD string as a timestamp directly
    When you convert a string like "20240520" straight to a long, you get the number 20240520. But Java's date APIs (like Date or Instant) use Unix timestamps—which are milliseconds since 1970-01-01 00:00:00 UTC. 20240520 milliseconds is only about 234 days, so that lands you right in early 1970. That's why your date is stuck in the epoch year.

  2. Using the wrong date format pattern
    The 49 in 01-49-1970 tells me you probably used DD (which means day of the year) instead of dd (day of the month) in your formatter. For example, if you used new SimpleDateFormat("MM-DD-YYYY"), the formatter would take the 49th day of 1970 and display it as 01-49-1970 (even though January only has 31 days—since it's counting the total days in the year, not the month).

How to Fix It

You need to properly parse the YYYYMMDD string into a date object first, then convert that to a timestamp if you need a long. Here are two approaches, depending on your Java version:

This is the modern, thread-safe way to handle dates—ditch the old SimpleDateFormat if you can:

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.ZoneId;

public class DateFix {
    public static void main(String[] args) {
        String dateInput = "20240520";
        
        // Define the format matching your input string
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // Parse the string into a LocalDate (no time zone attached)
        LocalDate date = LocalDate.parse(dateInput, inputFormatter);
        
        // If you need a long timestamp (milliseconds since epoch), add a time zone and convert
        long timestamp = date.atStartOfDay(ZoneId.systemDefault())
                             .toInstant()
                             .toEpochMilli();
        
        // Verify with correct formatting
        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern("MM-dd-yyyy");
        System.out.println(outputFormatter.format(date)); // Outputs 05-20-2024
        System.out.println(timestamp); // Correct epoch millis for 2024-05-20 00:00:00
    }
}

Option 2: Use the Old SimpleDateFormat (Legacy Compatibility)

If you're stuck with Java 7 or older, be aware this class is not thread-safe:

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

public class LegacyDateFix {
    public static void main(String[] args) throws ParseException {
        String dateInput = "20240520";
        
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        // Parse the string to a Date object
        Date date = formatter.parse(dateInput);
        
        // Get the timestamp as a long
        long timestamp = date.getTime();
        
        // Switch to the correct output format
        formatter.applyPattern("MM-dd-yyyy");
        System.out.println(formatter.format(date)); // Outputs 05-20-2024
        System.out.println(timestamp);
    }
}
Quick Reminders
  • Never convert YYYYMMDD strings directly to longs—they're not timestamps. Timestamps count milliseconds since 1970, while YYYYMMDD is just a numeric representation of the date.
  • Watch your format characters: yyyy = 4-digit year, MM = month, dd = day of month. YYYY is week-based year, DD is day of year—mixing these up causes weird outputs like you saw.
  • Stick with java.time if possible—it fixes almost all the flaws of the old date APIs.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 09:38:22