Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a Date from just Month and Year in Java?

Tags:

I need to generate a new Date object for credit card expiration date, I only have a month and a year, how can I generate a Date based on those two? I need the easiest way possible. I was reading some other answers on here, but they all seem too sophisticated.

like image 930
antonpug Avatar asked Sep 19 '12 16:09

antonpug


People also ask

How do you create a date object with day month and year?

Use the Date() constructor to create a date from the day, month and year values, e.g. const date = new Date(2022, 0, 24) . The Date() constructor takes the year, a zero-based value for the month and the day as parameters and returns a Date object.

How do I create a specific date in Java?

You can create a Date object using the Date() constructor of java. util. Date constructor as shown in the following example. The object created using this constructor represents the current time.

How can I get tomorrow date in dd mm yyyy format in Java?

get(Calendar. DAY_OF_MONTH) + 1; will it display tomorrow's date. or just add one to today's date? For example, if today is January 31.


Video Answer


2 Answers

You could use java.util.Calendar:

Calendar calendar = Calendar.getInstance(); calendar.clear(); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.YEAR, year); Date date = calendar.getTime(); 
like image 78
Reimeus Avatar answered Sep 21 '22 05:09

Reimeus


java.time

Using java.time framework built into Java 8

import java.time.YearMonth;  int year = 2015; int month = 12; YearMonth.of(year,month); // 2015-12 

from String

YearMonth.parse("2015-12"); // 2015-12 

with custom DateTimeFormatter

import java.time.format.DateTimeFormatter;  DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM yyyy"); YearMonth.parse("12 2015", formatter); // 2015-12 

Conversions To convert YearMonth to more standard date representation which is LocalDate.

LocalDate startMonth = date.atDay(1); //2015-12-01 LocalDate endMonth = date.atEndOfMonth(); //2015-12-31 
like image 39
Przemek Avatar answered Sep 22 '22 05:09

Przemek