Displaying the last two digits of the current year in Java
Asked Answered
P

7

30

How can I display only the last two digits of the current year without using any substring algorithms or any third party libraries?

I have tried the below method and it gave a four-digit year. I want to know whether there are any date formatting options available to get the current year in two-digit format.

Calendar.getInstance().get(Calendar.YEAR);
Propose answered 19/11, 2013 at 11:26 Comment(0)
C
44

You can use a SimpleDateFormat to format a date as per your requirements.

DateFormat df = new SimpleDateFormat("yy"); // Just the year, with 2 digits
String formattedDate = df.format(Calendar.getInstance().getTime());
System.out.println(formattedDate);

Edit: Depending on the needs/requirements, either the approach suggested by me or the one suggested by Robin can be used. Ideally, when dealing with a lot of manipulations with the Date, it is better to use a DateFormat approach.

Camporee answered 19/11, 2013 at 11:27 Comment(0)
O
77

You can simply use the modulo operator:

int lastTwoDigits = Calendar.getInstance().get(Calendar.YEAR) % 100;

Edit: Using a SimpleDateFormat, as @R.J proposed, is the better solution if you want the result to be a string. If you need an integer, use modulo.

Octal answered 19/11, 2013 at 11:27 Comment(1)
Seems like a clever solution at first but will result in a 1 digit number for years such as "2001" or 0 if it's like "2100"Venetis
C
44

You can use a SimpleDateFormat to format a date as per your requirements.

DateFormat df = new SimpleDateFormat("yy"); // Just the year, with 2 digits
String formattedDate = df.format(Calendar.getInstance().getTime());
System.out.println(formattedDate);

Edit: Depending on the needs/requirements, either the approach suggested by me or the one suggested by Robin can be used. Ideally, when dealing with a lot of manipulations with the Date, it is better to use a DateFormat approach.

Camporee answered 19/11, 2013 at 11:27 Comment(0)
D
16

This is a one-liner:

    System.out.println(Year.now().format(DateTimeFormatter.ofPattern("uu")));

I am using java.time.Year, one of a number of date and time classes introduced in Java 8 (and also backported to Java 6 and 7). This is just one little example out of very many where the new classes are more convenient and lead to clearer code than the old classes Calendar and SimpleDateFormat.

If you just wanted the two-digit number, not as a string, you may use:
Year.now().getValue() % 100.

The other answers were good answers in 2013, but the years have moved on. :-)

Edit: New Year doesn’t happen at the same time in all time zones. To make the dependency on time zone clear in the code I would usually write Year.now(myDesiredTimeZoneId), for example in the form Year.now(ZoneId.systemDefault()).

Designedly answered 9/4, 2017 at 9:53 Comment(0)
T
4

String.format() also has Date/Time Conversions.

To get the last two digits of the current year,

String.format("%ty", Year.now());

This works with a number of the java.time classes, including Year, YearMonth, LocalDate, LocalDateTime, and ZonedDateTime.

Transoceanic answered 28/5, 2020 at 23:41 Comment(0)
I
1

In Kotlin

Call this function and pass time in parameter

Example :
Input Parameter : "2021-08-09T16:01:38.905Z"
Output : 09 Aug 21

private val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private val outputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")

        fun calculateDateMonthYear(time: String): String {
            val inputTime = inputFormat.parse(time)
            val convertDateMonthYear = outputFormat.format(inputTime!!)
            val timeInMilliseconds = outputFormat.parse(convertDateMonthYear)!!
            val mTime: Calendar = Calendar.getInstance()
            mTime.timeInMillis = timeInMilliseconds.time
            val date_cal = SimpleDateFormat("dd")
            val month_date = SimpleDateFormat("MMM")
            val year_cal = SimpleDateFormat("yy")
            val date = date_cal.format(mTime.time)
            val month_name = month_date.format(mTime.time)
            val year = year_cal.format(mTime.time)
            return "$date $month_name $year"
        }
Inference answered 9/8, 2021 at 10:31 Comment(1)
Don’t use SimpleDateFormat. That class had severe design problems and has been outdated the last 10 years. Use java.time as shown in a couple of the answers. It works great in Kotlin too (or may consider kotlin.time, which is inspired by java.time). In addition hardcoding Z as a literal in the format pattern is wrong. Z is an offset of 0 and needs to be parsed and formatted as an offset to get correct results.Designedly
B
0

The solution of @Robin Krahl is a bit hacky but I like it. We could avoid the cases commented by @Albert Tong if we add a leading zero. In order that we have the last two digits of the year, I suppose that the result should be a String. In case we could not use the solution of @jaco0646. We could do this:

 String yearStr = addLeadingZero(Calendar.getInstance().get(Calendar.YEAR) % 100)

 private String addLeadingZero(int num) {
   String result = String.valueOf(num);
    if(num < 10){
        result = "0" + result;
    }

    return result;
}
Bifoliate answered 4/12, 2020 at 12:47 Comment(0)
K
0

I know the question asked for how to do this in Java but Google sent me here when asking about Groovy, so I'll add my answer for that here.

I came up with this based on the Java answer provided by Rahul:

String lastTwoYearDigits = new Date().format("yy")
Kirsten answered 31/5, 2022 at 19:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.