Disable future dates on date picker in android

Wednesday 20 December 2017

How to convert a Date to a formatted String

I assume you would like to reverse the date format?

SimpleDateFormat can be used for parsing and formatting. 
You just need two formats, one that parses the string and the other that returns the desired print out:

SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmt.parse(dateString);

SimpleDateFormat fmtOut = new SimpleDateFormat("dd-MM-yyyy");
return fmtOut.format(date);
Example:

// (1) get today's date
Date today = Calendar.getInstance().getTime();

// (2) create a date "formatter" (the date format we want)
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hh.mm.ss");

// (3) create a new String using the date format we want
String folderName = formatter.format(today);
    
// (4) this prints "Folder Name = 2009-09-06-08.23.23"

System.out.println("Folder Name = " + folderName)


SimpleDateFormat - many other custom date formats:

yyyy-MM-dd                 results in    2009-09-06
yyyyMMdd                   results in    20090906
EEE MMM dd hh:mm:ss yyyy   results in    Sun Sep 06 08:32:51 2009


SimpleDateFormat: Easily get the date, time, or datetime

// prints "Sep 6, 2009"
DateFormat dateInstance = SimpleDateFormat.getDateInstance();
System.out.println(dateInstance.format(Calendar.getInstance().getTime()));

// prints "9:03:20 PM"
DateFormat timeInstance = SimpleDateFormat.getTimeInstance();
System.out.println(timeInstance.format(Calendar.getInstance().getTime()));
  
// prints "Sep 6, 2009 9:03:20 PM"
DateFormat dateTimeInstance = SimpleDateFormat.getDateTimeInstance();
System.out.println(dateTimeInstance.format(Calendar.getInstance().getTime()));


No comments:

Post a Comment