使用 SimpleDateFormat 的问题

发布于 2024-12-28 21:47:32 字数 921 浏览 3 评论 0原文

显然,我错过了一些基本的东西。我在格式化 jspinner 的值时遇到问题。我尝试了几种不同的方法,但不断收到错误,没有跟踪它们,除了它与我试图从 jspinner 获取价值的方式有关。

这是微调器代码:

//setup date format for both spinners
SimpleDateFormat datePattern = new SimpleDateFormat("MM/dd/yyyy");
JSpinner dateFrom = new JSpinner(new SpinnerDateModel());
dateFrom.setEditor(new JSpinner.DateEditor(dateFrom, datePattern.toPattern()));
JPanel dateFromPanel = new JPanel(new GridLayout());
dateFromPanel.add(dateFrom);
dateFromPanel.setBorder(new TitledBorder("Date - From"));

这是我当前尝试获取格式的方式:

SimpleDateFormat sdfSource = new SimpleDateFormat("MM/dd/yyyy");
Date from = sdfSource.parse(dateFrom.getValue().toString());
SimpleDateFormat sdfDestination = new SimpleDateFormat("MM/dd/yyyy");           
String dosFrom = sdfDestination.format(from);

当前错误: 线程“main”中出现异常 java.text.ParseException:无法解析的日期:“Mon Oct 23 00:00:00 EDT 2006”

Apparently, I'm missing something fundamental. I'm having a problem with formatting the value of a jspinner. I've tried a couple different ways and keep receiving an error, didn't keep track of them, other than it has to do with how I'm trying to grab the value from jspinner.

Here is the spinner code:

//setup date format for both spinners
SimpleDateFormat datePattern = new SimpleDateFormat("MM/dd/yyyy");
JSpinner dateFrom = new JSpinner(new SpinnerDateModel());
dateFrom.setEditor(new JSpinner.DateEditor(dateFrom, datePattern.toPattern()));
JPanel dateFromPanel = new JPanel(new GridLayout());
dateFromPanel.add(dateFrom);
dateFromPanel.setBorder(new TitledBorder("Date - From"));

Here is how I'm currently trying to get the format:

SimpleDateFormat sdfSource = new SimpleDateFormat("MM/dd/yyyy");
Date from = sdfSource.parse(dateFrom.getValue().toString());
SimpleDateFormat sdfDestination = new SimpleDateFormat("MM/dd/yyyy");           
String dosFrom = sdfDestination.format(from);

Current error:
Exception in thread "main" java.text.ParseException: Unparseable date: "Mon Oct 23 00:00:00 EDT 2006"

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

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

发布评论

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

评论(4

橪书 2025-01-04 21:47:32

我怀疑问题是这样的:

dateFrom.getValue().toString()

我怀疑 dateFrom.getValue() 只是返回一个 Date - 当然它没有任何关联的格式。你不应该解析它,而应该直接投射它:

Date from = (Date) dateFrom.getValue();

当然,我可能是错的......但这将是我的第一个想法。

I suspect the problem is this:

dateFrom.getValue().toString()

I suspect dateFrom.getValue() is just returning a Date - which of course doesn't have any associated format. Instead of parsing that, you should just cast it:

Date from = (Date) dateFrom.getValue();

I could be wrong, of course... but that would be my first thought.

や三分注定 2025-01-04 21:47:32

您必须阅读有关 JSpinners 的教程并设置

noreferrer">SpinnerDateModel for JSpinner instace,那么您就不需要从 JSpinner简单示例 来使用SpinnerDateModel

在此处输入图像描述

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

public class TimeZoneSpinners {

    private final String[] zones = {"Asia/Tokyo", "Asia/Hong_Kong",
        "Asia/Calcutta", "Europe/Paris", "Europe/London",
        "America/New_York", "America/Los_Angeles"
    };
    private final JLabel[] labels = new JLabel[zones.length];
    private final SimpleDateFormat[] formats = new SimpleDateFormat[zones.length];
    private JSpinner spinner;
    private SpinnerDateModel model;
    private SimpleDateFormat format;
    private JPanel panel;
    private JFrame frame = new JFrame();

    public void makeUI() {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        model = new SpinnerDateModel();
        model.setValue(date);
        spinner = new JSpinner(model);
        spinner.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Date date = (Date) ((JSpinner) e.getSource()).getValue();
                for (int i = 0; i < labels.length; i++) {
                    labels[i].setText(formats[i].format(date));
                }
            }
        });
        format = ((JSpinner.DateEditor) spinner.getEditor()).getFormat();
        format.setTimeZone(TimeZone.getTimeZone(zones[0]));
        format.applyPattern("yyyy-MM-dd HH:mm:ss");
        panel = new JPanel(new GridLayout(zones.length, 2, 10, 10));
        for (int i = 0; i < zones.length; i++) {
            formats[i] = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
            formats[i].setTimeZone(TimeZone.getTimeZone(zones[i]));
            JLabel label = new JLabel(zones[i]);
            labels[i] = new JLabel(formats[i].format(date));
            panel.add(label);
            panel.add(labels[i]);
        }
        frame.setLayout(new BorderLayout(10, 10));
        frame.add(spinner, BorderLayout.NORTH);
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TimeZoneSpinners().makeUI();
            }
        });
    }
}

you have to read tutorial about JSpinners and to set SpinnerDateModel for JSpinner instace, then you couldn't needed to solve parsing Date instance from JSpinner

simple example for usage of SpinnerDateModel

enter image description here

import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;

public class TimeZoneSpinners {

    private final String[] zones = {"Asia/Tokyo", "Asia/Hong_Kong",
        "Asia/Calcutta", "Europe/Paris", "Europe/London",
        "America/New_York", "America/Los_Angeles"
    };
    private final JLabel[] labels = new JLabel[zones.length];
    private final SimpleDateFormat[] formats = new SimpleDateFormat[zones.length];
    private JSpinner spinner;
    private SpinnerDateModel model;
    private SimpleDateFormat format;
    private JPanel panel;
    private JFrame frame = new JFrame();

    public void makeUI() {
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        model = new SpinnerDateModel();
        model.setValue(date);
        spinner = new JSpinner(model);
        spinner.addChangeListener(new ChangeListener() {

            @Override
            public void stateChanged(ChangeEvent e) {
                Date date = (Date) ((JSpinner) e.getSource()).getValue();
                for (int i = 0; i < labels.length; i++) {
                    labels[i].setText(formats[i].format(date));
                }
            }
        });
        format = ((JSpinner.DateEditor) spinner.getEditor()).getFormat();
        format.setTimeZone(TimeZone.getTimeZone(zones[0]));
        format.applyPattern("yyyy-MM-dd HH:mm:ss");
        panel = new JPanel(new GridLayout(zones.length, 2, 10, 10));
        for (int i = 0; i < zones.length; i++) {
            formats[i] = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
            formats[i].setTimeZone(TimeZone.getTimeZone(zones[i]));
            JLabel label = new JLabel(zones[i]);
            labels[i] = new JLabel(formats[i].format(date));
            panel.add(label);
            panel.add(labels[i]);
        }
        frame.setLayout(new BorderLayout(10, 10));
        frame.add(spinner, BorderLayout.NORTH);
        frame.add(panel, BorderLayout.CENTER);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TimeZoneSpinners().makeUI();
            }
        });
    }
}
单身情人 2025-01-04 21:47:32

我怀疑这是因为您的 JSpinner#getValue() 方法返回了一个 Date 并且您不需要解析它。您可以尝试仅替换为

Date from = (Date) dateFrom.getValue();

Calling Date.toString() 始终返回与当前语言环境相同的默认格式的日期(“Mon Oct 23 00:00:00 ...”),这就是为什么您在尝试解析它时遇到异常。

I suspect it's because your JSpinner#getValue() method is returning a Date and you don't need to parse it. You might try replacing with just

Date from = (Date) dateFrom.getValue();

Calling Date.toString() always returns a date in the same default format for the current locale ("Mon Oct 23 00:00:00 ...") which is why you're getting an exception on trying to parse it.

放手` 2025-01-04 21:47:32

您应该使用

String dosFrom = sdfDestination.format((Date) dateFrom.getValue());

问题是 dateFrom 实际上返回选定的日期,而 Date.toString() 不会以您使用的格式返回日期。

You should use

String dosFrom = sdfDestination.format((Date) dateFrom.getValue());

The problem is that dateFrom actually returns the selected date, and Date.toString() doesn't return the date in the format you use.

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