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

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

问题描述

我试图用 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?

附注.我从 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");

使用它来将字符串解析为日期,然后使用其他 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天全站免登陆