Home » Scala language

How to get the current year as an integer in Scala?

Scala | getting a current year as an integer: Scala has active libraries to work on date and time that provide you to every part of the date and time as an object. In this tutorial, we will learn how to get the current year as an integer in Scala?
Submitted by Shivang Yadav, on July 29, 2019

In Scala programming language, there is an option for the programmer to use libraries of java because of its interoperability with java.

There are a few methods to extract the date of a program,

1) Java 8 Year

The java.time.year library is used to get the value of the current year.

Syntax:

val data_int = Year.now.getvalue

Program:

import java.time.Year

object MyClass {
    def main(args: Array[String]) {
        val year: Int = Year.now.getValue; 
        printf(" "+year)
    }
}

Output

2019

2) Java 8 localDate

The java.time.localDate library is used to get the current date and we can extract year also using its method.

Synatx:

val data_int = LocalDate.now.getvalue

Example:

import java.time.LocalDate

object MyClass {
    def main(args: Array[String]) {
        val year: Int = LocalDate.now.getYear; 
        printf(" "+year)
    }
}

Output

2019

3) Java Calendar

The java.util.calendar is used to to get calendar information using the getInstance method. And passing the Calendar.YEAR to it will return the value of Year.

Synatx:

val year = Calendar.getInstance.get(Calendar.YEAR)

Example:

import java.util.Calendar

object MyClass {
    def main(args: Array[String]) {
        val year: Int = Calendar.getInstance.get(Calendar.YEAR); 
        printf(" "+year)
    }
}

Output

2019


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.