I'm makeing an app that want some text color Change when current time between 2 date.
like I have schedule with tasks, and from 1:00PM to 5:00PM there is a task I have to do.
Want to make a condition if current time between two date change the color of this text.
it's not just about color.
it's a lot of things put it's depend on this condition
Puted the two date in one TextView
val simpleDateFormat = SimpleDateFormat("h:mm a")
val time = simpleDateFormat.format(item.startDate) + "-" + simpleDateFormat.format(item.endDate)
looks like your item.startDate and item.endDate are Date instances. so you need also a Date with current time, which you can get with
val currDate = Calendar.getInstance().getTime()
or even by creating new Date instance (is set to current by default)
val currDate = Date()
now you can convert Date to long timestamp
val startDateAsTimestamp = item.startDate.getTime()
val endDateAsTimestamp = item.endDate.getTime()
val currDateAsTimestamp = currDate.getTime()
and now your if would be
if (currDateAsTimestamp >= startDateAsTimestamp &&
currDateAsTimestamp <= endDateAsTimestamp) {
Related
I am using below function to take the today's date :
fun getCurrentDateTime(dateFormat: String): String {
val Datetime: String
val c = Calendar.getInstance()
val dateformat = SimpleDateFormat(dateFormat, Locale.getDefault())
Datetime = dateformat.format(c.time)
return Datetime
}
I have filter for today to sort fetch today's filtered data. But, With the above function I am filtering with the same values,
Means start date for Today and end date for Today are both same.
I want it different.
Means :
Start Date should be 1639560609 (Wednesday, 15 December 2021 00:00:00 GMT+05:30)
and
End Date should be Current time (which I am getting with above function)
So, The Issue you got that I want the Today's start Date with start time of the day.
How ? Thanks.
Use LocalDateTime to get current date and start of the day
val dateFormatter = DateTimeFormatter.ofPattern("EEEE, d MMMM yyyy HH:mm:ss")
val localDate = LocalDate.now() // your current date time
val startOfDay: LocalDateTime = localDate.atStartOfDay() // date time at start of the date
val timestamp = startOfDay.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() // start time to timestamp
Log.d("Date:", "start date $timestamp")
Log.d("Date:", "start date parsed ${startOfDay.format(dateFormatter)}")
Output:
Start Date Timestamp : 1639506600000
Parsed TimeStamp: Wednesday, 15 December 2021 00:00:00
Edit : To get end of date time
val endOfDate: LocalDateTime = localDate.atTime(LocalTime.MAX)
val timestampEnd = endOfDate.atZone(ZoneId.of("UTC")).toInstant().epochSecond
Capture the current moment.
Instant now = Instant.now() ;
Understand that, for any given moment, the date varies around the globe by time zone. At one moment, it can be “tomorrow” in Tokyo Japan 🇯🇵 while simultaneously “yesterday” in Edmonton Alberta Canada 🇨🇦.
Specific time zone
Get the date in effect at that moment in a specific time zone. Here we use the time zone of India 🇮🇳.
ZoneId zKolkata = ZoneId.of( "Asia/Kolkata" ) ;
LocalDate todayKolkata = now.atZone( zKolkata ).toLocalDate() ;
Get the first moment of the date in that zone.
ZonedDateTime startOfTodayKolkata = todayKolkata.atStartOfDay( zKolkata ) ;
Get the count of whole seconds from first moment of 1970 UTC to that first moment of that date in Kolkata.
long secondsSinceEpochToStartOfTodayKolkata = startOfTodayKolkata.toInstant().getEpochSecond() ;
If you want to track the full length of the day, use Half-Open approach. In Half-Open, the beginning is inclusive while the ending is exclusive. So a full day starts at the first moment of one date and runs up to, but does not include, the beginning of the following day.
ZonedDateTime startOfTomorrowKolkata = todayKolkata.plusDays( 1 ).atStartOfDay( z ) ;
Track the full day as a pair of Instant objects, using the Interval class from the ThreeTen-Extra library.
Interval allDayTodayKolkata = Interval.between( startOfTodayKolkata , startOfTomorrowKolkata ) ;
UTC (offset of zero)
In contrast, determine the first moment of today’s date as experienced with an offset of zero hours-minutes-seconds.
LocalDate todayUtc = now.atOffset( ZoneOffset.UTC ).toLocalDate() ;
ZonedDateTime startOfDayUtc = todayUtc.atStartOfDay( ZoneOffset.UTC ) ;
long secondsSinceEpochToStartOfDayUtc = startOfDayUtc.toInstant().getEpochSecond() ;
Here is how can you can get the number of hours later time from current time in Kotlin:
https://stackoverflow.com/a/73050414/7126848
I am new to Kotlin. Which is the best way to get startDate and endDate of a week by pressing previous button to move one week backwards and next button to move one week forward?
The text showing the dates defaults to the current week. I want when a user presses next to be able to update the text with the next week's start and end dates and vice versa when the user presses previous
You did not mention which day of week is actually determining a start of an end of a week in your situation/culture/country.
That's why I can only come up with a fun that accepts a java.time.DayOfWeek as the only argument and calculates the next java.time.LocalDate with that DayOfWeek in the future. Fortunately, Kotlin provides the concept of extension functions, which means you can simply attach a new fun to LocalDate like this:
fun LocalDate.getNext(weekday: DayOfWeek): LocalDate {
// add one day to have tomorrow
var next = this.plusDays(1)
// then start checking the days of week until the given one is reached
while (next.dayOfWeek != weekday) next = next.plusDays(1)
// when reached, return the result
return next
}
You can use it in a main like this:
fun main() {
val today = LocalDate.now()
println("Today ($today) is ${today.dayOfWeek.getDisplayName(TextStyle.FULL, Locale.ENGLISH)}")
val nextFriday = today.getNext(DayOfWeek.FRIDAY)
println("Next Friday is $nextFriday")
val nextMonday = today.getNext(DayOfWeek.MONDAY)
println("Next Monday is $nextMonday")
}
This outputs
Today (2021-11-25) is Thursday
Next Friday is 2021-11-26
Next Monday is 2021-11-29
Ok, that's only half of your requirements, but I think you are able to write (nearly) the same fun that gets you the date of the previous day of week instead of the upcoming one. Let's call it getPrevious(weekday: DayOfWeek), for example.
Here is example how to get startWeekDate.
private fun getStartWeekDate(){
val cal = Calendar.getInstance()
val currentDayOfWeek = cal.get(Calendar.DAY_OF_WEEK)
val daysAfterSunday = currentDayOfWeek - Calendar.SUNDAY
cal.add(Calendar.DATE, -daysAfterSunday)
val theDateForSunday = cal.time
}
for the endDate()
private fun getEndWeekDate(){
val cal = Calendar.getInstance()
val currentDayOfWeek = cal.get(Calendar.DAY_OF_WEEK)
val daysBeforeSaturday = currentDayOfWeek - Calendar.SATURDAY
cal.add(Calendar.DATE, -daysBeforeSaturday)
val theDateForSaturday = cal.time
}
I have a fragment that has a RecyclerView of six items (meaning every day of the week from Monday to Saturday). Is there any way to display the current date (day and month) on all these elements, so that the countdown starts from Monday of the current week?
You can get this using LocalDate.
val thisWeekMonday = LocalDate.now()
.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY))
val daysOfThisWeek = List(7) { thisWeekMonday + Period.ofDays(it) }
You can use DateTimeFormatter to convert it to a human-readable String for use in your List that you put in the RecyclerView. For example:
val formatter = DateTimeFormatter.ofPattern("EEEE, MMMM d")
val formattedDaysOfThisWeek = daysOfThisWeek.map { it.format(formatter) }
I have a simple code where i want to convert a certain given time to another time zone , in my case the time is local to UK , but i need to convert the time to another timezone if the user lives in different country , i have tried this simple code but it is not working for me , it is giving me random hour 04:00
any help would be appreciated guys
This is the code
var localTime = "16:00" // simulating time to Uk timezone
localtime.text = localTime
timeZone.setOnClickListener {
val localTimes = "16:00"
val timeFormatter = SimpleDateFormat("hh:mm", Locale.UK)
val timezone = TimeZone.getDefault() // get device timezone
timeFormatter.timeZone = timezone
val timeToFormat = timeFormatter.parse(localTimes)
val formattedTime = timeFormatter.format(timeToFormat)
localtime.text = formattedTime
}
Under my locale DateFormat.getTimeInstance(DateFormat.SHORT).format(...) gives me 8:28 AM. Is there any way to get localized time but with leading zero (that is, 08:28 AM in my case) - I mean without hardcoding pattern etc?
If you want to have 24H format time you can do something like this using kotlin extensions:
fun Long.formatTime(): String? {
val calendar = Calendar.getInstance()
calendar.time = Date(this)
val hour = calendar.get(Calendar.HOUR_OF_DAY)
val minute = calendar.get(Calendar.MINUTE)
return String.format("%02d:%02d", hour, minute)
}
EDITED
If you still did't find the solution
val dateFormat = SimpleDateFormat("hh:mm a", Locale.getDefault())
print(dateFormat.format(Date()))
This prints
08:24 AM