Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Date in java with just year

Tags:

java

date

format

My aim is to get a date in the format '{current year}-01-01 00:00:00' i.e. only the value for year changes with time. What is the best way to do that.

Using

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-01-01 00:00:00");
String format = simpleDateFormat.format(new Date());

doesnt seem clean enough.What other options do I have?

like image 594
Ankit Dhingra Avatar asked May 22 '26 14:05

Ankit Dhingra


2 Answers

You should use a Calendar object. Much easier to manage, and if you need to get to a date there are methods for that.

  Calendar cal = Calendar.getInstance();
 //Set to whatever date you want as default
  cal.set(Calendar.YEAR, *year you want*);
like image 180
RMT Avatar answered May 25 '26 05:05

RMT


You can use a Calendar object with the following code:

Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(Calendar.YEAR, year);
like image 22
Anthony Grist Avatar answered May 25 '26 05:05

Anthony Grist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!