简体   繁体   English

转换日期格式不起作用

[英]Convert date format not working

hello guys I've been on this issue for 4 hours and I don't seem able to solve it. 大家好,我已经在这个问题上待了4个小时,但我似乎无法解决。 I want the date selected using JDateChooser to be converted to this format dd-mm-yyyy but I couldn't do this. 我希望将使用JDateChooser选择的日期转换为这种格式dd-mm-yyyy,但是我不能这样做。 This what I wrote but it prints the date as :Thu Aug 21 00:00:00 WEST 2014. I want it to be printed 21-08-2014 This is my code: 这是我写的内容,但其打印日期为:2014年8月21日星期四00:00:00 WEST2014。我希望将其打印为21-08-2014这是我的代码:

public void addIns() {
    JTextField ch=(JTextField) dateChooser.getDateEditor().getUiComponent();
    SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy");
    try{
        Date date = df.parse(ch.getText());
        } catch(Exception e){System.out.println("wrong date");}
      System.out.println(date);   }

The format Thu Aug 21 00:00:00 WEST 2014 is the default format of the Date.toString method. 格式Thu Aug 21 00:00:00 WEST 2014是Date.toString方法的默认格式。

So, if you are expecting: 因此,如果您期望:

System.out.println(date);

To print 21-08-2014, then you are wrong. 要打印2014年8月21日,那么您错了。

You could: 你可以:

  • in Java 8 use LocalDate and LocalTime, and have a decent toString (but that won't print 21-08-2014). 在Java 8中使用LocalDate和LocalTime,并具有不错的toString(但不会打印2014年8月21日)。
  • print the date with the format method, eg: df.format(date); 用format方法打印日期,例如: df.format(date);

And, since you are using Swing - and Swing components - there is probably a better way to get or set the format on the component. 而且,由于您正在使用Swing-和Swing组件-可能有一种更好的方法来获取或设置组件的格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM