无法解析的日期:Java 中的 "Apr 5, 2018"

Unparseable date: "Apr 5, 2018" in Java

我只想要 Month,Year 的输出,但我遇到了问题。它是 Unparseable date: "Apr 5, 2018"Exception。我已将日期存储在 sqliteBill_Date 列中,它的字段格式为 "Apr 5, 2018"。那么我怎样才能只获得 (Apr, 2018) 格式的月份和年份。这是我下面给出的代码:

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

public class Demo2 {
    private static Connection con;
    private static String query;
    private static PreparedStatement PStat,PStat2;
    private static ResultSet res,res2;
    private static String Bill_Date;
public static void main(String args[])
{
    try
    {
        con=Database.Database();
        query="select Bill_Date from DailySales where Bill_Date='Apr 5, 2018'";
        PStat=con.prepareStatement(query);
        res=PStat.executeQuery();
        while(res.next())
        {
        Bill_Date=res.getString("Bill_Date");
        }
        SimpleDateFormat month=new SimpleDateFormat("MMMM,yyyy",Locale.ENGLISH);
        SimpleDateFormat dateformat=new SimpleDateFormat("MMM-dd,YYYY");
        Date date=dateformat.parse(Bill_Date);
        String MONTH=month.format(date);
        System.out.println(MONTH);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
}
}

它有这个错误。

java.text.ParseException: Unparseable date: "Apr 5, 2018"
    at java.text.DateFormat.parse(Unknown Source)
    at Demo2.main(Demo2.java:34)

格式化程序中缺少 space,您还有一个额外的 -:

SimpleDateFormat dateformat=new SimpleDateFormat("MMM dd, yyyy");

谢谢@David

另外你的年份格式好像不对。使用 yyyy 以获得正确的年份格式。

两个问题:

  1. 大写 Y 表示 "week year",与年份不同。请改用 ys。
  2. 您的 - 格式在日期字符串中不存在。使格式具有 space(或使数据具有 -)。

使用这个:

SimpleDateFormat dateformat = new SimpleDateFormat("MMM d,yyyy");