Kotlin date time comparison - kotlin

I am trying to figure out how this works. My initial date is: "2022-11-06T08:39:16.307Z"
So now I did this:
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
sdf.timeZone = TimeZone.getTimeZone("UTC")
val time: Long = sdf.parse("2022-11-06T08:39:16.307Z").time
val calendar = Calendar.getInstance()
val currentTime = calendar.timeInMillis
val diff = (currentTime - time) / 1000
Difference is negative number but it should be positive as other date is in past. Yes I hate working with dates in general but can not figure out why it works like this.

Related

convert LocalDateTime to Date by using kotlin

I have a java.time.LocalDateTime and i want to convert it in java.util.Date
val myLocalDateTime = LocalDateTime.now().plusDays(5)
I want to convert LocalDateTime.now().plusDays(5) to java.util.Date in kotlin.
How Can i do it?
You need to add mandatory information in order to make a LocalDateTime convertable to a java.util.Date…
Before you try, think about if you can use Instant.now(), because the methods for legacy compatibility require Instants as arguments:
fun main() {
// get "now" as Instant
val now = Instant.now()
// print the java.util.Date created from the Instant
println(Date.from(now))
// use the Instant plus 5 days to create another date
val date = Date.from(now.plus(5, ChronoUnit.DAYS))
// create a formatter for the Date
val formatter = SimpleDateFormat("yyyy-MM-dd")
// and print it using the formatter
println(formatter.format(date))
}
Output (some moments ago on my middle-european machine):
Thu Feb 09 15:31:06 CET 2023
2023-02-14
If you really need to use a LocalDateTime, which has no zone or offset, you will have to add one, convert the result (a ZonedDateTime or an OffsetDateTime) toInstant() and create Dates from those…
If it's all about dates (year, month of year, day of month) without time of day, you could simply use a java.time.LocalDate:
fun main() {
// get "today" as LocalDate
val today = LocalDate.now()
// print it using toString() implicitly
println(today)
// add five days
val fiveDaysLater = today.plusDays(5)
// and print it formatted by a prebuilt formatter
println(fiveDaysLater.format(DateTimeFormatter.ISO_LOCAL_DATE))
}
Output:
2023-02-10
2023-02-15

Kotlin: How to detect 'date change'?

I will use Timer() to execute function by 5 minutes in Kotlin.
And when I execute function by 5m, if a day passed,I want count var to be 0.
So my idea was
declare two vars
var todayDate = LocalDate.now() // 2019-09-23
var todayCount:Int = 0
After that I will check this vars in 5 minutes by using Timer()
Then todayDate value differs from previous todayDate, then I can detect date change.
However, I don't know how to compare current todayDate and previous todayDate.
Any idea? or is there any other way to know day change?
For your specific question about comparing dates you can use the isEqual() method on your LocalDate instance (docs). Something like the following would likely do what you want:
// initial state
var todayDate = LocalDate.now()
var todayCount = 0
// in each timer iteration:
val now = LocalDate.now()
if (!todayDate.isEqual(now)) {
// it's a new day
todayCount = 0
todayDate = now
} else {
// it's the same day
++todayCount
}
However if you're talking about Android and using its Timer class, you need to be aware that that runs on a background thread and you will need to persist your todayDate and todayCount values somewhere (which could be app preferences, your app DB, etc.).

Kotlin Unparseable and - NullPointerException error

What I expect: the 'for loop' brings the number of columns that will be displayed in the table, the start date, and the end date are taken by an object. the transaction date is taken by a different object. The start date variable gets the exception and the transaction date gets the value without a problem.
Code:
if(date >0){//no of dates for the selected week
for (i in 0 until date) {
val dateFormat = SimpleDateFormat("yyyy-MM-dd")
val tv_Date = TextView(this)
val transDate = SortedDateHashMap[i].transactionDate
val start = SortedExpenseDateHashMap[i]!!.weekStart
val end = SortedExpenseDateHashMap[i]!!.weekEnd
val startDate = dateFormat.parse(start)
val endDate = dateFormat.parse(end)
var transactionDat = dateFormat.parse(transDate)
if(transactionDat.before(endDate) && transactionDat.after(startDate)){
setColor(tv_Date)
tv_Date.setPadding(10, 15, 10, 10)
tv_Date.gravity = Gravity.CENTER
tv_Date.layoutParams = params3
tv_Date.text = SortedDateHashMap[i].transactionDate
}
}
}
Used null safe and wrote the code in the try..catch exception. Worked

Android(Kotlin) Material Design Date Range Picker How to set Minimum and Maximum dates properly?

I have a Date Range Picker(Material Design) and I want to disable previous dates(so minimum date will be current day), and maximum date will be 6 months later. I tried something like this:
val calendar = Calendar.getInstance()
val constraintsBuilderRange = CalendarConstraints.Builder()
val dateValidatorMin: CalendarConstraints.DateValidator = DateValidatorPointForward.from(calendar.timeInMillis)
val dateValidatorMax: CalendarConstraints.DateValidator = DateValidatorPointBackward.before(calendar.timeInMillis+100000000)
val listValidators = ArrayList<CalendarConstraints.DateValidator>()
listValidators.add(dateValidatorMin)
listValidators.add(dateValidatorMax)
val validators = CompositeDateValidator.allOf(listValidators)
constraintsBuilderRange.setValidator(validators)
val datePicker = MaterialDatePicker.Builder.dateRangePicker()
.setTitleText("Select range")
.setCalendarConstraints(constraintsBuilderRange.build())
.build()
datePicker.show(
this.requireFragmentManager(),"date_range_picker"
)
This worked but I randomly give 100000000 to dateValidatorMax. So how can I achieve 6 months later in milliseconds? And how can I get 1 day before currentDate in dateValidatorMin?
So I solved this problem thanks to Kotlin, there is a really easy method:
val dateValidatorMin: CalendarConstraints.DateValidator = DateValidatorPointForward.from(calendar.timeInMillis - 1.days.toLong(
DurationUnit.MILLISECONDS))
val dateValidatorMax: CalendarConstraints.DateValidator = DateValidatorPointBackward.before(calendar.timeInMillis+ 180.days.toLong(
DurationUnit.MILLISECONDS))
I had a similar problem where I needed only dates in the range from the previous day to 45 days behind the current date to be enabled. That is, today, January 18th, the calendar would only be enabled from 12-05-2022 to 01-17-2023.
I did it like this:
val dateValidatorMin: DateValidator =
DateValidatorPointForward.from(
Calendar.getInstance().timeInMillis - 45.days.toLong(DurationUnit.MILLISECONDS))
val dateValidatorMax: DateValidator =
DateValidatorPointBackward.before(
Calendar.getInstance().timeInMillis - 1.days.toLong(DurationUnit.MILLISECONDS))
val dateValidator: DateValidator = CompositeDateValidator.allOf(listOf(dateValidatorMin, dateValidatorMax))
val constraints: CalendarConstraints =
CalendarConstraints.Builder()
.setValidator(dateValidator)
.build()
val builder = MaterialDatePicker.Builder.dateRangePicker()
.setCalendarConstraints(constraints)
.setTitleText(getString(R.string.label_select_date_range))
val picker = builder.build()
And the result was like this:
Hope this helps.

Kotlin - How to get time ("HH:mm") from string Date

How can I get the time from a json where I have values like:
"time": ["1507457400000", "1507458600000"] //Strings
In Javascript I could do something like
new Date(1507457400000) // return Sun Oct 08 2017 12:10:00 GMT+0200
new Date(1507457400000).getHours() // return 12
new Date(1507457400000).getMinutes() // return 10
But I have no idea how to get the time using kotlin. Any idea what is the best way to get the time from the data I have?
val date = SimpleDateFormat("HH:mm").format(Date((1507457400000 / 1000)))
Use this:
val calendar = Calendar.getInstance()
calendar.timeInMillis = 1507457400000
val date = calendar.time
if you have the millisecond in a string like str:
val calendar = Calendar.getInstance()
calendar.timeInMillis = str.toLong()
val date = calendar.time
for hour and min:
val h = calendar.get(Calendar.HOUR_OF_DAY)
val m = calendar.get(Calendar.MINUTE)
val result = h.toString() + ":" + m.toString()