-2

Is there a way to get only the year from the Date class and parse it into a string? Here is the code that I use:

Date d1 = new Date();
d1.getYear();  `

And how to set the date to DatTime.Now;

like in C#?

Dexter90
  • 69
  • 2
  • 14

2 Answers2

2

Use SimpleDateFormat.

SimpleDateFormat sdf  = new SimpleDateFormat("yyyy");
System.out.println(sdf.format(new Date()));

Output:

2014
Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
1
public static String getCurrentDate(String format) {
    SimpleDateFormat sdfFrom = new SimpleDateFormat(format);
    Calendar currentTime = Calendar.getInstance();
    return (sdfFrom.format(currentTime.getTime()));
}

public static Date getCurrentDate() {
    Calendar currentTime = Calendar.getInstance();
    return currentTime.getTime();
}

try to use java 8 date 
Ran Adler
  • 3,587
  • 30
  • 27