Gregorian Calendar give wrong day number

I’ve the below code, where I’m trying to post a sales order transaction, with date and qty, once I’, getting the day of the transaction date, it is lagging 31 days, and apparently the Dec 1st is considered to be day number 1 in he year!! Anything wrong in my code, or how can I fix it?!

import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.*

data class transaction (var date: LocalDate, var quantity: Double) {

    private var calendar: Calendar = 
            GregorianCalendar(date.year, date.monthValue, date.dayOfMonth)
    var day: Int
        get() = calendar.get(Calendar.DAY_OF_YEAR)
        set(value) = TODO()
}

val formatter: DateTimeFormatter
    get() = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)

fun main(args: Array<String>) {
    var salesOrders = ArrayList<transaction>()
    salesOrders.add(transaction(LocalDate.parse("01.01.2018", formatter), 5.0))

    println(salesOrders[0].date.dayOfMonth) // prints: 1
    println(salesOrders[0].date.monthValue) // prints: 1
    println(salesOrders[0].date.year)       // prints: 2018
    println(salesOrders[0].day)             // prints 32 ??!!
}

The problem is that the value returned by LocalDate.monthValue goes from 1 to 12 which means 1 = January, while the GregorianCalendar constructor accepts a 0-based month value, which means that 0 = January.
So basically you are creating a GregorianCalendar with a 1-month offset from the LocalDate, which is why when you read the day property you get the day of year of February 1st instead of January 1st

1 Like

Incidentally, I’m not sure why you’re obtaining the day of the year via the GegorianCalendar class when the LocalDate class already has a getDayOfYear() method?

1 Like