简体   繁体   中英

How to set format of current date time to different format?

I use the following code to retrieve the current date and time, then add it to table using following method.

 Change 2013-07-29 23:20:34.0 to 29th July 2013, 11:20 PM

DateTime

 public Date getCurrentDateTime() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        System.out.println("current:" + dateFormat.format(date));
        return date;
    }

Hibernate

@Temporal(javax.persistence.TemporalType.TIMESTAMP)
    public Date getCurrentDateTime() {
        return date;
    }

A Date object doesn't have a format. (Neither java.sql.Date nor java.util.Date .) The database will just store it in the table in whatever native representation it chooses (almost certainly not text) and when you retrieve the data it's up to you to format it how you wish.

To change the format used by System.out.println , just change the pattern you're passing to the SimpleDateFormat constructor - see the documentation for details. Note that you should consider which time zone and Locale you're interested in, too - for example, month names won't be the same between different locales, and different locales also have different expected formats. (Even within the same language, there are different conventions.)

You'll find the "th" of "29th" hard to handle with SimpleDateFormat - I don't believe it supports ordinals. This question may help you though. (It's going to be ugly code, mind you - I would suggest changing the format to remove the ordinal if you possibly can.)

To change the day to ordinal number you need to use the following suffix . have a look at this link as well

DD +     TH = DDTH  result >>>> 4TH

OR to spell the number add SP to the format

DD + SPTH = DDSPTH   result >>> FOURTH

Also use the fmt library to format the date on jsp pages

 <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>

 <fmt:formatDate type="both" dateStyle="long" timeStyle="short" 
      value="${date}"/>

Something similar to this ??

for hibernate

SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String dateBufferString = format.format(date);
Date dateBuffer;
try {

dateBuffer = format.parse(dateBufferString);
System.out.println("Database Date Format :" + date);
System.out.println("(dd-MM-yyyy) date: " + format.format(date));
System.out.println("dateBufferSTring " + dateBufferString);
System.out.println("dateBuffer: " + dateBuffer);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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