如何将字符串转换为日期并保持格式正确

发布于 2024-12-14 08:29:55 字数 3726 浏览 2 评论 0原文

我正在从文本文件中读取 String ,其中包含 yyMMdd 形式的日期,然后我想将其转换为 date 类型,但是当我这样做时,它就会失去格式。这是我尝试过的示例

String strDate = matcher.group(10); // strDate would contain 111107

SimpleDateFormat formatter1 = new SimpleDateFormat("yyMMdd");
Date date = formatter1.parse(strDate); // after parsing it, the format changes to Thu Nov 03 00:00:00 EDT 2011

但是如果我将 date 放入字符串中,就像这样 String tDate = formatter1.format(date); 然后字符串包含我希望看到的格式的日期 111107

我有办法做到这一点吗?也许我可以如何调用 format 函数来返回 date 对象而不是 String,谢谢。

编辑 我从文件中读取日期列表并将其加载到地图中,然后将这些日期与同样采用 yyMMdd 格式的当前日期进行比较,然后如果地图中的日期大于比当前日期早一周,我提示用户输入,然后将日期和其他相关信息以 yyMMdd 格式写入文件。我使用地图的原因是文本文件的每一行都包含一些信息和唯一的名称,并且我比较了该特定数据行的日期,因此我

在此处 执行 map.get(aName)是代码,希望有帮助

dbConnect();
            stmt = conn.createStatement();
            String query = "select * from OBJECT_BAC_EV where instance = 12";//VALUE <> 'Normal'";
            rslt = stmt.executeQuery(query);

            Calendar currentDate = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
            String dateNow = formatter.format(currentDate.getTime());
            Date curDate = (Date)formatter.parse(dateNow);
            currentDate.setTime(curDate);
            currentDate.add(Calendar.DAY_OF_MONTH, -7);
            dateNow = formatter.format(currentDate.getTime());
            curDate = (Date)formatter.parse(dateNow);

            Calendar cDate = Calendar.getInstance();
            SimpleDateFormat f = new SimpleDateFormat("yyMMdd");
            String strDate = f.format(cDate.getTime());

            while(rslt.next())
            {
                System.out.println(rslt.getRow());

                String aValue = rslt.getString("VALUE");
                String aName = rslt.getString("NAME");
                String aObjRef = rslt.getString("ObjRef");


                if(aNoteMap.containsKey(aName))
                {

                    String n = aNoteMap.get(aName);
                    if(aDateMap.get(aName).before(curDate))
                    {
                        int answer = JOptionPane.showConfirmDialog(null, "Would you like to use last weeks note? " + n, "Hey", JOptionPane.YES_NO_OPTION);
                        if( answer == JOptionPane.YES_OPTION)
                        {
                            output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + aDateMap.get(aName) + "    "
                                     + n  + (System.getProperty("line.separator")));
                        }
                        else if( answer == JOptionPane.NO_OPTION)
                        {
                            String newNote = JOptionPane.showInputDialog("Enter new note");
                            output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + aDateMap.get(aName) + "    "
                                     + newNote  + (System.getProperty("line.separator")));
                        }
                    }
                    else
                        output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + aDateMap.get(aName) + "    "
                                 + n  + (System.getProperty("line.separator")));
                }
                else
                    output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + strDate + "    "
                            + ""  + (System.getProperty("line.separator")));
            }
            System.out.println("its closing output..");
            output.close();
        }

I am reading in a String from a text file which contains a date in the form of yyMMdd I then want to convert it to type date but when I do that it loses its format. here is an exmaple of what I have tried

String strDate = matcher.group(10); // strDate would contain 111107

SimpleDateFormat formatter1 = new SimpleDateFormat("yyMMdd");
Date date = formatter1.parse(strDate); // after parsing it, the format changes to Thu Nov 03 00:00:00 EDT 2011

But if I take date and put it back into a string like so String tDate = formatter1.format(date); the string then contains the date in the format Id like to see 111107.

Is there a way I can do this? maybe if I could some how call the format function to return a date object instead of String, thanks.

Edit
I read a list of dates in from a file and load them into a map I then compare those dates to the current date which is also in the yyMMdd format and then if the date from the map is more then a week earlier than the current date I prompt the user for input and then write the date and other related info to a file, in the yyMMdd format. The reason I use a map is each line of the text file contains some information and a unique name, and I compared the date for that specific line of data so I do a map.get(aName)

here is the code, hope it helps

dbConnect();
            stmt = conn.createStatement();
            String query = "select * from OBJECT_BAC_EV where instance = 12";//VALUE <> 'Normal'";
            rslt = stmt.executeQuery(query);

            Calendar currentDate = Calendar.getInstance();
            SimpleDateFormat formatter = new SimpleDateFormat("yyMMdd");
            String dateNow = formatter.format(currentDate.getTime());
            Date curDate = (Date)formatter.parse(dateNow);
            currentDate.setTime(curDate);
            currentDate.add(Calendar.DAY_OF_MONTH, -7);
            dateNow = formatter.format(currentDate.getTime());
            curDate = (Date)formatter.parse(dateNow);

            Calendar cDate = Calendar.getInstance();
            SimpleDateFormat f = new SimpleDateFormat("yyMMdd");
            String strDate = f.format(cDate.getTime());

            while(rslt.next())
            {
                System.out.println(rslt.getRow());

                String aValue = rslt.getString("VALUE");
                String aName = rslt.getString("NAME");
                String aObjRef = rslt.getString("ObjRef");


                if(aNoteMap.containsKey(aName))
                {

                    String n = aNoteMap.get(aName);
                    if(aDateMap.get(aName).before(curDate))
                    {
                        int answer = JOptionPane.showConfirmDialog(null, "Would you like to use last weeks note? " + n, "Hey", JOptionPane.YES_NO_OPTION);
                        if( answer == JOptionPane.YES_OPTION)
                        {
                            output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + aDateMap.get(aName) + "    "
                                     + n  + (System.getProperty("line.separator")));
                        }
                        else if( answer == JOptionPane.NO_OPTION)
                        {
                            String newNote = JOptionPane.showInputDialog("Enter new note");
                            output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + aDateMap.get(aName) + "    "
                                     + newNote  + (System.getProperty("line.separator")));
                        }
                    }
                    else
                        output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + aDateMap.get(aName) + "    "
                                 + n  + (System.getProperty("line.separator")));
                }
                else
                    output.write(aName + "    "  + aObjRef + "    "  + aValue + "    "  + strDate + "    "
                            + ""  + (System.getProperty("line.separator")));
            }
            System.out.println("its closing output..");
            output.close();
        }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

挖个坑埋了你 2024-12-21 08:29:55

Date 类没有“内部”格式,它仅表示日期元素。要使用特定格式输出它,您需要按照您的方式进行操作: String tDate = formatter1.format(date);

您认为它具有“错误格式”的原因可能是因为当当您尝试输出它时,它默认执行 toString() ,这不会按照您想要的方式格式化它。

如果您向我们提供有关如何使用该日期的更多详细信息(包括您的代码),那么我们也许能够提供有关如何将格式化程序注入其中的建议。

The Date class has no "internal" format, it only represents date elements. To output it using a specific format, you need to do the way you did: String tDate = formatter1.format(date);

The reason why you think it has the "wrong format" is probably because when you try to output it, it does a toString() by default, which doesn't format it the way you want.

If you give us more details about how you want to use that date (include your code), then we might be able to provide suggestions on how to inject the formatter into it.

遗忘曾经 2024-12-21 08:29:55

Date 始终存储包括时间在内的完整信息。如果您使用不包含时间信息的 SimpleDateFormat 解析日期,这些字段将设置为 0,如示例中所示。

Date 本身不存储任何格式信息。

Date always stores the complete information including time. If you parse the date with a SimpleDateFormat that does not contain time info, these fields are set to 0 as in your example.

Date does not store any format info itself.

盛夏尉蓝 2024-12-21 08:29:55

SimpleDateFormat.format 方法始终返回一个字符串。它将“日期”参数表示为具有指定格式的字符串。例如:

SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd');
Date date = sdf.parse("110510");
String sDate = sdf.format(date); //"110510"

SimpleDateFormat sdf2 = new SimpleDateFormat('yyyy.MM.dd');
String sDate2 = sdf2.format(date); //2011.05.10  

这是格式化日期对象的最佳选择。

The SimpleDateFormat.format method always returns a String. It represents the 'date' parameter as a String, with the specified format. For example:

SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd');
Date date = sdf.parse("110510");
String sDate = sdf.format(date); //"110510"

SimpleDateFormat sdf2 = new SimpleDateFormat('yyyy.MM.dd');
String sDate2 = sdf2.format(date); //2011.05.10  

It's the best thing for formatting a Date Object.

海风掠过北极光 2024-12-21 08:29:55

使用 joda-time 编写,它会像这样:

String str = "110107";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .appendYearOfCentury(2, 2)
  .appendMonthOfYear(2)
  .appendDayOfWeek(2)
  .toFormatter();

DateTime dateFromDB = formatter.parseDateTime(str);//create DateTime instance
System.out.println("Date:" + formatter.print(dateFromDB));//toString in required format

而且它还有很多其他好处,显然它将取代现有的 Java 日期库在即将发布的 Java 版本中一直是相当痛苦的。

好处之一是

DateTime now = new DateTime();
Integer compared = now.minusWeeks(1).compareTo(dateFromDB);

compareTo 可以实现预期

Written using joda-time, it would like this :

String str = "110107";
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
  .appendYearOfCentury(2, 2)
  .appendMonthOfYear(2)
  .appendDayOfWeek(2)
  .toFormatter();

DateTime dateFromDB = formatter.parseDateTime(str);//create DateTime instance
System.out.println("Date:" + formatter.print(dateFromDB));//toString in required format

And it has many other benefits, apparently it will replace the existing Java date libs, which have always been rather painful, in upcoming java releases.

One of the benefits is

DateTime now = new DateTime();
Integer compared = now.minusWeeks(1).compareTo(dateFromDB);

And compareTo does the expected

夏夜暖风 2024-12-21 08:29:55

您可以尝试类似的操作:

class MyDate extends java.util.Date {
  static final SimpleDateFormat yymmddFormat = new SimpleDateFormat("yyMMdd");

  public MyDate (String s) throws ParseException {
    super(yymmddFormat.parse(s).getTime());
  }

  public String toString () {
    return yymmddFormat.format(this);
  }
}

在当前使用 Date 对象的任何地方都使用此类。这将使您的所有约会看起来都如您所愿。

You could try something like:

class MyDate extends java.util.Date {
  static final SimpleDateFormat yymmddFormat = new SimpleDateFormat("yyMMdd");

  public MyDate (String s) throws ParseException {
    super(yymmddFormat.parse(s).getTime());
  }

  public String toString () {
    return yymmddFormat.format(this);
  }
}

Use this class everywhere you currently use a Date object. This should make all your dates look as you want them.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文