【问题标题】:Parser pattern for monthOfYear that is not zero-padded with no literal text separationmonthOfYear 的解析器模式,它不是零填充且没有文字文本分隔
【发布时间】:2015-09-05 21:37:29
【问题描述】:

是否可以使用 jodatime 解析日期 8302011?在一种不那么痛苦的格式中,它看起来像8/30/2011,我将其模式化为MM/dd/yyyy。

我尝试过的:

  • 模式Mddyyyy
    • 8302011 -> Cannot parse "8302011": Value 83 for monthOfYear must be in the range [1,12]
    • 12302011 -> 2011-12-30T00:00:00.000Z

幸运的是,日期不是模棱两可的,因为day 始终表示为两位数。但是,月份是一位数或两位数。

我意识到将左侧的零填充到 8 个字符很简单,但在这种情况下,我无法做到这一点。

【问题讨论】:

  • @JasonSperske 你是对的。这确实有效,幸运的是我使用的是DateTimeFormatterBuilder,所以我可以指定最小和最大数字。不幸的是,您似乎无法在模式字符串中指定它。
  • SO 是一个很好的输入来源,所以我采取了这个问题来改进my own date/time-library。谢谢你。不幸的是,Joda-Time(和 JSR-310 也一样)不支持这种模式。尽管您使用构建器找到了一个很好的解决方法,但我建议您向 Joda-Time-issue-tracker 提交问题。然后,您可能有机会在 Joda-Time 的未来版本中实现此功能。

标签: java jodatime


【解决方案1】:

我知道下面的内容与 jodatime 不同,但您可以尝试使用 SimpleDateFormat 来解析日期作为替代日期

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

/**
 * Created by luan on 9/12/16.
 */
public class DateTimeFormatTest {
    public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("Mddyyyy");
    public SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("MM/dd/yyyy");

    public Date getDate(String source){
        Date date = null;
        try {
            date = simpleDateFormat.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return date;
    }
    public String parseStringValue(Date date){
        String result = "";
        result = simpleDateFormat2.format(date);
        return result;
    }

    public static void main(String[] args) {
        DateTimeFormatTest obj = new DateTimeFormatTest();
        Date date = obj.getDate("8302011");
        System.out.println(date);
        String result = obj.parseStringValue(date);
        System.out.println(result);
    }
}

输出:

Tue Aug 30 00:00:00 ICT 2011
08/30/2011

【讨论】:

    猜你喜欢
    • 2017-01-02
    • 1970-01-01
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多