简体   繁体   English

无法将String解析为日期格式

[英]Can't parse String to date format

I cant figure out why this code won't work. 我不明白为什么此代码将无法正常工作。 Could anyone help me 谁能帮我

String dateStr = "Thu Apr 02 09:49:16 CEST 2015";
DateFormat readFormat = new SimpleDateFormat( "EEE MMM dd HH:mm:ss z yyyy");

DateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
        try {
            date = readFormat.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        String formattedDate = "";
        if (date != null) {
            formattedDate = writeFormat.format(date);
        }

        System.out.println(formattedDate);

My read format should be good unless im missing something. 我的阅读格式应该不错,除非我错过了一些东西。

I always get an java.text.ParseException: Unparseable date: "Thu Apr 02 09:49:16 CEST 2015" 我总是得到一个java.text.ParseException:无法解析的日期:“ 2015年4月2日星期四09:49:16 CEST”

On line: date = readFormat.parse(dateStr); 在线:date = readFormat.parse(dateStr);

I tried the code on http://ideone.com/oBwtQo and it works there too. 我在http://ideone.com/oBwtQo上尝试了该代码,它也在那里工作。 Why wont this work in NetBeans on my PC. 为什么在我的PC上的NetBeans中无法正常工作。

尝试这个

DateFormat readFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.US);

The code works fine, please check your imports, you would these classes 该代码工作正常,请检查您的导入,您将使用这些类

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

This one is working perfectly 这个很完美

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

public class Test {
public static void main(String[] args)
{
    String dateStr = "Thu Apr 02 09:49:16 CEST 2015";
    DateFormat readFormat = new SimpleDateFormat( "EEE MMM dd HH:mm:ss z yyyy");
    DateFormat writeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = null;
    try {
        date = readFormat.parse(dateStr);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    String formattedDate = "";
    if (date != null) {
        formattedDate = writeFormat.format(date);
    }
    System.out.println(formattedDate);
    }
}

Output: 2015-04-02 13:19:16 输出:2015-04-02 13:19:16

Please check your imports 请检查您的进口

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

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