Java日期和时间格式 [英] Java Date and Time Formatting

查看:150
本文介绍了Java日期和时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化时间,以便用户可以输入一段时间。

I am trying to format time so that the user can enter a time.

 b1.setStartTime(JOptionPane.showInputDialog("Enter Start time for Booking: "));

有没有办法为上面的代码做这个?

Is there a way of doing this for the code above?

我已经尝试将预订课程的startTime更改为Timestamp
,而在主要尝试使用此代码:

I have tried changing the startTime in booking class to a Timestamp and in the main tried to use this code:

DateFormat timeFormatter =
    DateFormat.getTimeInstance(DateFormat.SHORT, b1.getStartTime());

但是我很难围绕着我的头。所有我想要做的是允许用户输入一个时间作为短版本,例如上午7:20然后我可以使用这个时间与SQL数据库进行比较。

But i struggle to wrap my head around it. All i want to do is allow the user to input a time as the short version e.g. 7:20 AM. and then i can use this time to compare against an SQL database.

对我来说,DateFormat.getTimeInstance()看起来像是要走的路。如果我使用这种方式,应该在预订类中的startTime类型为Date,我如何能够格式化用户输入?

To me the DateFormat.getTimeInstance() seems like the way to go. Should startTime in booking class be of type Date if i were to use this and how would i be able to format the user input?

推荐答案

p> SimpleDateFormat可能对你很方便:

SimpleDateFormat might be convenient for you:

 tf = new java.text.SimpleDateFormat ("h:mm a") 

您可以使用它来解析一段时间:

You can use it to parse a time:

 Date d = tf.parse (textfield.getText ());

另一方面,输出以下格式的日期/时间:

and the other way round, output a date/time in this format:

 System.out.println ("Time: " + tf.fomat (date)); 

这篇关于Java日期和时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆