How to get date in Android (Kotlin)

1.1k views Asked by At

I am a beginner in Android and I need code to get today number (from local date). Like this way:
A var is Iday. And today is 8th October so Iday should be equal to 8.

2

There are 2 answers

0
Arvind Kumar Avinash On

LocalDate#getDayOfMonth

import java.time.LocalDate;

public class Main {
    public static void main(String[] args) {
        // Today at the default time-zone (your JVM's time-zone)
        LocalDate date = LocalDate.now();

        // Day of month today
        int dayOfMonth = date.getDayOfMonth();

        // Display
        System.out.println("Today, the day of month is " + dayOfMonth);
    }
}

Output:

Today, the day of month is 8

If you want to get today's date at some other time zone, use LocalDate now(ZoneId zone) as shown below:

import java.time.LocalDate;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        // Today at Melbourne
        LocalDate date = LocalDate.now(ZoneId.of("Australia/Melbourne"));

        // Day of month today
        int dayOfMonth = date.getDayOfMonth();

        // Display
        System.out.println("Today, the day of month is " + dayOfMonth);
    }
}

Output:

Today, the day of month is 9
1
iknow On

You can use Callendar and get method.

import java.util.*

val cal = Calendar.getInstance()
val dayOfMonth =  cal[Calendar.DAY_OF_MONTH]

println(dayOfMonth) // 8 -> 8th October 2020

getInstance():

Gets a calendar using the default time zone and locale. The Calendar returned is based on the current time in the default time zone with the default locale.


Deprecated:

import java.util.*

val currentTime = Calendar.getInstance().time
println(currentTime.date) // 8