开发者

Java String to Date without time

开发者 https://www.devze.com 2023-01-06 10:27 出处:网络
I\'m taking a class in Java and I need to convert a string to a date format (dd/MM/yyyy). I have been using the Simp开发者_如何学GoleDateFormat to format my input, but it is showing the time, timezone

I'm taking a class in Java and I need to convert a string to a date format (dd/MM/yyyy). I have been using the Simp开发者_如何学GoleDateFormat to format my input, but it is showing the time, timezone and day of the week the date falls. Here is a snippet of my code:

SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy"); 
Date date = new Date(); 
do{ 
    y = JOptionPane.showInputDialog(null, 
                                    "Please enter the vehicle's registration date",
                                    "Year?", 
                                    JOptionPane.QUESTION_MESSAGE); 
    try { 
        date = df.parse(y); 
        check = true; 
    } 
    catch (ParseException e) { 
        check = false; 
    } 
} 
while (check == false); 
return date;

Anyone know how I can keep the format to just the date (e.g. 12/3/2000)? Thanks


Just format it accordingly using SimpleDateFormat#format().

String dateString = new SimpleDateFormat("dd/MM/yyyy").format(dateObject);

The java.util.Date object contains information about both date and time. If you want only the date part in a human representable format, then you need to format it into a String. Invoking Date#toString() as you would get when doing System.out.println(dateObject) would only return the date in format dow mon dd hh:mm:ss zzz yyyy. Also see the linked javadoc.


I have a similar solution to @BalusC, except this one will provide a locale-dependent formatting:

String dateString = java.text.DateFormat.getDateInstance().format(dateObject);

In other words your US and EU customers will get different formatting. One they're familiar with.

0

精彩评论

暂无评论...
验证码 换一张
取 消