calculate the difference of days between two dates in kotlin - android

I need to in my application to be able to calculate the difference of days between two dates. I tried a few ways that would give us the difference between the days of the future, but I need to get the past right as well.
I try with val currentTime = Calendar.getInstance().time

Oh boy, you haven't realized it yet, but you just opened pandoras box: Time is very weird (especially in the past) and it is not as simple as calculating the difference between two timestamps. If you want to understand the insanity, I highly recommend this video by Tom Scott.
But anyway, to your question:
import java.time.Duration
import java.time.LocalDate
val firstTimestampInclusive = LocalDate.of(2000, 2, 27)
val secondTimestampExclusive = LocalDate.of(2000, 3, 1)
val numberOfDays = Duration.between(firstTimestampInclusive.atStartOfDay(), secondTimestampExclusive.atStartOfDay()).toDays()
println("Number of days between $firstTimestampInclusive and $secondTimestampExclusive: $numberOfDays")
This will print the following:
Number of days between 2000-02-28 and 2000-03-01: 2
Edit: For many reasons, using java.util.Date and java.util.Calendar is discouranged and you should use java.time instead (as I usggested in my answer).

val cal = Calendar.getInstance()
cal.time = date1
val day1 = cal.get(Calendar.DAY_OF_YEAR)
val cal2 = Calendar.getInstance()
cal2.time = date2
val day2 = cal2.get(Calendar.DAY_OF_YEAR)
day1 and day2 are integers between 0-365

Related

Get time from LocalDateTime

I'm looking to get the time from LocalDateTime (unless there is an easier way) with the format of HH:mm:a (12:34 pm)
Which Date/Time formatter do I want to use?
val sdf = SimpleDateFormat("HH:mm:a")
val dt = LocalDateTime.now().format(sdf)
print("Time: $dt")
I just managed to accomplish that the other way. Look at my code bellow.
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
fun main() {
val sdf = DateTimeFormatter.ofPattern("hh:mm:a")
val dt = LocalDateTime.now().format(sdf)
println("Time: $dt")
}
Reference:
Kotlin Program to Get Current Date/Time
tl;dr
(Using Java syntax.)
myLocalDateTime
.toLocalTime() // Extract the time only, without the date portion.
.format( // Automatically localize.
DateTimeFormatter
.ofLocalizedTime( FormatStyle.SHORT )
.withLocale( Locale.US )
)
Details
The Answer by Luiz is correct. I can show a couple of alternatives: extracting the time only, and automatically localizing.
If you want to focus on the time of day, extract a LocalTime object.
LocalTime lt = myLocalDateTime.toLocalTime() ;
Rather than hard-code a specific format, it is generally best to let java.time automatically localize.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedTime( FormatStyle.SHORT ).withLocale( Locale.US ) ;
String output = lt.format( f ) ;

Get startDate and endDate of week when pressing forward button or previous button

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
}

Get week start and end days from week number

I want to get the start and end dates of a given week number. I have tried the following code but it always returns the same date (the current week)
val c: Calendar = Calendar.getInstance()
val week = 39
c.set(Calendar.WEEK_OF_YEAR, week)
val firstDayOfWeek = c.firstDayOfWeek
c.set(Calendar.DAY_OF_WEEK,firstDayOfWeek)
startDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek+6)
endDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
I solved it by calling c.time an extra time before using it. Here's the working code :
val c: Calendar = Calendar.getInstance()//Locale.getDefault())
val week = 39
c.set(Calendar.WEEK_OF_YEAR, week)
val t = c.time;
val firstDay = c.firstDayOfWeek
c.set(Calendar.DAY_OF_WEEK,firstDay)
startDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
c.set(Calendar.DAY_OF_WEEK,firstDay+6)
endDate = SimpleDateFormat("yyyy-MM-dd",Locale.getDefault()).format(c.time).toString()
Cannot understand why it works, tried it after reading this https://developer.android.com/reference/java/util/Calendar#field-manipulation
You must be missing something or making some basic mistake. Given below is the proof:
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
int week = 39;
Calendar c = Calendar.getInstance();
c.set(Calendar.WEEK_OF_YEAR, week);
int firstDayOfWeek = c.getFirstDayOfWeek();
// Start date
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek);
String startDate = sdf.format(c.getTime());
System.out.println(startDate);
// End date
c.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + 6);
String endDate = sdf.format(c.getTime());
System.out.println(endDate);
}
}
Output:
2020-09-21
2020-09-27
Note: I do not know Kotlin but AFAIK, you can run Java code also in Kotlin. If you want to stick to Kotlin syntax, I hope you should be able to convert it easily into Kotlin syntax.

Localized time with leading zero

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

Difference between two datetime formats in android?

As i am new to android development I am unable to find code for calculating the difference between two datetime formats. My question is.
I am using webservice in my project where i am getting datetime response as follows..
starttime :- [2012-11-04 10:00:00]
endtime :- [2012-11-04 12:00:00]
Here i want to display on screen as
Today Timings :- 2012-11-04 2 hours
Means need to calculate the difference between two dates and need to display the time difference on screen.
Can anyone please help me with this.
Given you know the exact format in which you are getting the date-time object, you could use the SimpleDateFormat class in Android which allows you to parse a string as a date given the format of the date expressed in the string. For your question:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date startTime = sdf.parse(<startTime/endTime String>, 0);
Similarly parse your endtime, and then the difference can be obtained using getTime() of the individual objects.
long diff = endTime.getTime() - startTime.getTime()
Then it's as simple as converting the difference to hours using:
int hours = (int)(diff/(60*60*1000));
Hope that helps.
java.time
Solution using java.time, the modern API:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("u-M-d H:m:s", Locale.ENGLISH);
LocalDateTime startTime = LocalDateTime.parse("2012-11-04 10:00:00", dtf);
LocalDateTime endTime = LocalDateTime.parse("2012-11-04 12:00:00", dtf);
long hours = ChronoUnit.HOURS.between(startTime, endTime);
System.out.println(hours);
}
}
Output:
2
Learn more about the the modern date-time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
If you're using java.util.Date; you're gonna have to use an intermediate variable. you can convert your dates to long values and subtract those and then convert your long back to a date.
long diff = new Date().getTime() - new Date(milliseconds).getTime();
Date dateDiff = new Date(diff);
But you should be warned that it doesn't take daylight savings and whatever else variables into account. if you're that scrupulous, you might be indulged with this replacement date class. It has the functionality you seek.
I use this code to get difference of two date.
public void getTimeDifference(Date endDate,Date startDate) {
Date diff = new Date(endDate.getTime() - startDate.getTime());
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar.setTime(diff);
int day=calendar.get(Calendar.DAY_OF_MONTH);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
}
}

Categories

Resources