Best way to convert Java SQL date from yyyy-MM-dd to dd format MMMM yyyy

Is there an easy way to convert Java SQL dates from yyyy-MM-dd format to dd MMMM yyyy format?

I could convert the date to a string and then manipulate it, but it's better to leave it as a Java SQL date. while I need to do this, the data has already been read from the MySQL database, so I cannot make changes there.

+3
source share
4 answers

An object, such as java.sql.Dateand java.util.Date(of which it java.sql.Dateis a subclass), does not have its own format. You use an object java.text.DateFormatto display these objects in a specific format, namely DateFormat(rather than itself Date), which defines the format.

For instance:

Date date = ...;  // wherever you get this
DateFormat df = new SimpleDateFormat("dd MMMM yyyy");
String text = df.format(date);
System.out.println(text);

Note. When you print an object Datewithout using the object DateFormat, for example:

Date date = ...;
System.out.println(date);

then it will be formatted using some default format. However, this default format is not a property of an object Datethat you can change.

+8
source

If this is for presentation, you can immediately use SimpleDateFormat:

package org.experiment;

import java.sql.Date;
import java.text.SimpleDateFormat;

public class Dates {
    private static SimpleDateFormat df = new SimpleDateFormat("MMMM yyyy");

    public static void main(String[] args){

        Date oneDate = new Date(new java.util.Date().getTime());
        System.out.println(df.format(oneDate));
    }

}
+6
source

, " Java SQL". java.sql.Date, ... . , - java.text.SimpleDateFormat.

Joda Time DateTime; Joda Time - API , . , SimpleDateFormat .

( : a java.sql.Date , java.util.Date, , .)

+5

TL;DR

myJavaSqlDate.toLocalDate()
             .format(
                 DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG )
                                  .withLocale ( Locale.UK )
             )

11 2017

, . , , . .

,

/ . .

JDBC - Java.

java.time

, Joda-Time. java.time.

java.sql.Date, java.time.LocalDate, toLocalDate, .

LocalDate ld = myJavaSqlDate.toLocalDate() ;

JDBC-, JDBC 4.2 java.time.

, . LocalDate. LocalDate .

, . java.time .

, :

...

LocalDate ld = LocalDate.now ( ZoneId.of ( "America/Montreal" ) );  // Today date at this moment in that zone.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate ( FormatStyle.LONG ).withLocale ( Locale.UK );
String output = ld.format ( f );

: 11 2017 .


java.time

java.time Java 8 . legacy , java.util.Date, Calendar SimpleDateFormat.

Joda-Time, , java.time.

, . Oracle. Qaru . JSR 310.

java.time?

The ThreeTen-Extra project extends java.time with additional classes. This project is proof of possible future additions to java.time. Here you can find useful classes, such asInterval,YearWeek,YearQuarterand longer .

+1
source

Source: https://habr.com/ru/post/1545320/


All Articles