Home > database >  How to get Current Date into String Format in Java? [duplicate]
How to get Current Date into String Format in Java? [duplicate]

Time:09-25

I am trying to get a QR code of current date for an attendance system. i am setting the value to a TextView. I am doing something like this..

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");
Date date = new Date();
String data = simpleDateFormat.format(date);
textView.setText(data);

I am supposed to get something like 25.09.2021

Instead I am getting java.text.SimpleDateFormat@44aa2260

what am i doing wrong?

CodePudding user response:

tl;dr

    LocalDate
    .now(
        ZoneId.of( "Africa/Tunis" )
    )
    .format(
        DateTimeFormatter.ofPattern( "dd.MM.uuuu" )
    )

Automatically localize:

LocalDate.now().format( DateTimeFormatter.ofLocalizedDate( FormatStyle.SHORT ) )

Or:

LocalDate
.now( ZoneId.of( "Asia/Kolkata" ) )
.format( 
    DateTimeFormatter
    .ofLocalizedDate( FormatStyle.SHORT )
    .withLocale( 
        new Locale( "hi" , "IN" ) 
    ) 
)

SimpleDateFormat#toString

As commented by Frisch, your actual code differs from what you showed in your Question. We know that because a value like java.text.SimpleDateFormat@44aa2260 is what is produced by SimpleDateFormat#toString, having inherited that method implementation from Object#toString.

So you must be calling something like textView.setText( simpleDateFormat );.

Another problem: Your formatting pattern is incorrect. The codes are case-sensitive. So mm should be MM.

java.time

You are using terrible date-time classes that are now legacy, supplanted years ago by the modern java.time classes defined in JSR 310.

I recommend being explicit about the time zone by which to determine today’s date rather than relying implicitly on the JVM’s current default time zone.

ZoneId z = ZoneId.of( "America/Edmonton" ) ;  // Or `ZoneId.systemDefault()`. 
LocalDate today = LocalDate.now( z ) ;

Specify your formatting pattern.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd.MM.uuuu" ) ;
String output = today.format( f ) ;

CodePudding user response:

DateFormat simpleDateFormat = new SimpleDateFormat("dd.mm.yyyy");
Date date = new Date();
String data = simpleDateFormat.format(date);
textView.setText(data);

Thanks @rooster123

CodePudding user response:

import java.text.SimpleDateFormat;
import java.util.Date;
public class CurrentDateTimeExample2 {
public static void main(String[] args) {
    SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy");
    Date date = new Date();
    System.out.println(formatter.format(date));
   }
}

Took reference from here

  • Related