如何解析日期? [英] How to parse a date?

查看:140
本文介绍了如何解析日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试用 SimpleDateFormat 解析这个日期,但它不起作用:

I am trying to parse this date with SimpleDateFormat and it is not working:

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

public class Formaterclass {
    public static void main(String[] args) throws ParseException{
        String strDate = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        Date dateStr = formatter.parse(strDate);
        String formattedDate = formatter.format(dateStr);
        System.out.println("yyyy-MM-dd date is ==>"+formattedDate);
        Date date1 = formatter.parse(formattedDate);

        formatter = new SimpleDateFormat("dd-MMM-yyyy");
        formattedDate = formatter.format(date1);
        System.out.println("dd-MMM-yyyy date is ==>"+formattedDate);
    }
}

如果我用strDate = 2008-10-14,我有一个积极的答案。有什么问题?如何解析此格式?

If I try this code with strDate="2008-10-14", I have a positive answer. What's the problem? How can I parse this format?

PS。我从 jDatePicker 得到这个日期,没有关于如何修改用户选择日期时所获得的日期格式的说明。

PS. I got this date from a jDatePicker and there is no instruction on how modify the date format I get when the user chooses a date.

推荐答案

您不能指望使用以不同格式设置的SimpleDateFormat解析日期。

You cannot expect to parse a date with a SimpleDateFormat that is set up with a different format.

要解析您的Thu Jun 18 20:56:02 EDT 2009日期字符串,您需要一个SimpleDateFormat(大致):

To parse your "Thu Jun 18 20:56:02 EDT 2009" date string you need a SimpleDateFormat like this (roughly):

SimpleDateFormat parser=new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

使用它来将字符串解析为Date,然后使用其他SimpleDateFormat将该日期转换为格式你想要的。

Use this to parse the string into a Date, and then your other SimpleDateFormat to turn that Date into the format you want.

        String input = "Thu Jun 18 20:56:02 EDT 2009";
        SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
        Date date = parser.parse(input);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = formatter.format(date);

        ...

JavaDoc: http://docs.oracle.com/javase/7/docs/api/java/text /SimpleDateFormat.html

这篇关于如何解析日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆