Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert Date in String Java

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.text.DateFormat;

public class MyClass {
    public static void main(String args[]) {
      Date scadenza = new Date();
      String date = MyClass.dateToString(scadenza, "YYYYMMDD");
      
      System.out.println(date);
    }
    
    public static String dateToString(Date date, String format){
        if(date == null) return null;
        final DateFormat df = new SimpleDateFormat(format);
        df.setTimeZone(TimeZone.getTimeZone("UTC"));
        return df.format(date);
    }
}

I have this piece of code in one of my software, i simplified it rewriting it in an example java class. Today is "2022-04-08" and when i execute this code the variable date is equal to "20220498" but it should be "20220408". How can solve this problem?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Try with "yyyyMMdd" as format param.
D is day in the year according to documentation.
Y is Week year.
https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

Ps. Ho visto che sei italiano, buon continuo su Stackoverflow!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading