Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a new Date object without the year parameter in Java?

I am trying to use new SimpleDateFormat to parse a string in the format dd-MM. Basically, I want to create a date object out of the string and persist in the database.

When I checked the database entry I see that it appends 1970 to the year column. I believe it is the default value of the year provided when it is empty. Is there a way to prevent the year value. I do not want to store information about the year.

My code -

String dateOfBirth = "14-Feb";
dbObject.save(new SimpleDateFormat("dd-MMM").parse(dateOfBirth));

For the sake of simplicity, assume dbObject.save() the method expects a date object to be provided. I do not want to create a date of value - 14-Feb-1970, instead it should be just 14-Feb.

like image 601
Boudhayan Dev Avatar asked Apr 28 '19 07:04

Boudhayan Dev


People also ask

How do you create a Date object with a specific format?

Creating A Simple Date Format A SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. String pattern = "yyyy-MM-dd" ; SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern); The specified parameter “pattern” is the pattern used for formatting and parsing dates.

How do you pass a Date object as a parameter in Java?

1) Using Date class Specify the desired pattern while creating the instance of SimpleDateFormat . Create an object of Date class. Call the format() method of DateFormat class and pass the date object as a parameter to the method.

How do you set a specific Date in Java?

The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT. Parameters: The function accepts a single parameter time which specifies the number of milliseconds. Return Value: It method has no return value.


1 Answers

I would strongly suggest you use the java.time.MonthDay class to store your dates. If your database doesn't support storing that, you can just store it as a string, and parse it when you get it out of the database.

Here is how you would parse your date:

MonthDay md = MonthDay.parse("14-Feb", DateTimeFormatter.ofPattern("dd-MMM").withLocale(Locale.US));

You can then store the string returned by .toString into the database (it will be something like --02-14), and the next time you parse it, you don't need a date time formatter:

MonthDay md = MonthDay.parse("--02-14");
like image 154
Sweeper Avatar answered Sep 30 '22 11:09

Sweeper