Localized time with leading zero - android

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

Related

calculate the difference of days between two dates in kotlin

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

Getting Date with Start time of the Day

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

Converting Time to another timezone

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
}

Struggle with parse function

So started learning Kotlin and Android studio coding.
I was following Youtube video
https://www.youtube.com/watch?v=z3_QgdmXGK4&t=994s&ab_channel=Dr.ParagShukla
I am making simple age calculator, however, cant make string to become date, so i could subtract input date with current date. Code looks exactly same as in the video.
Code compiles well and gets installed in android device, however, whenever press Calculate Age button, app stops responding because of var dob = sdf.parse(dob) function. I assume it cant convert the date from string to date format for further calculations. Thanks.
Code below:
fun openDatePicker(view: View) {
var c = Calendar.getInstance()
DatePickerDialog(
this,
DatePickerDialog.OnDateSetListener { datePicker, yy, mm, dd -> // listens what date picker has to say
var mm = mm + 1
var date = "$dd/ $mm /$yy "
TimePickerDialog(
this,
TimePickerDialog.OnTimeSetListener { timePicker, hh, mi ->
date += " $hh:$mi"
editTextTextPersonName.setText(date) // shows date in the line
},
c.get(Calendar.HOUR_OF_DAY),
c.get(Calendar.MINUTE),
true
).show()
}, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH)
).show()
}
fun Calculateage(view: View) {
var today = Date() // todays date
var dobs = editTextTextPersonName.text.toString() // takes value from input
var sdf = SimpleDateFormat("mm/MM/yy HH:mm")
var dob = sdf.parse(dobs) // converts the date to simple date, no can find difference
var days = (today.time - dob.time) / 86400000 // converts into mil secs, need to divide by milsecs in a day
var hours = (today.time - dob.time) % 86400000 / 3600000
var minutes = (today.time - dob.time) % 86400000 % 3600000 / 60000
var sec = (today.time - dob.time) % 86400000 % 3600000 % 60000/1000
textView.visibility = View.VISIBLE
textView.setText("Days = $days\nHours= $hours\nMinutes=$minutes\nSeconds = $sec")
}
Your SimpleDateFormat doesn't match your string value.
Your var date looks like var date = "$dd/ $mm /$yy $hh:$mi"
Your SimpleDateFormat has "mm/MM/yy HH:mm"
You should change your formatter to something like this:
"dd/ MM /yy HH:mm"

Formatting a calendar date

I just want the date to show up like so:
Saturday, May 26, 2012 at 10:42 PM
Here's my code so far:
Calendar calendar = Calendar.getInstance();
String theDate = calendar.get(Calendar.MONTH) + " " + calendar.get(Calendar.DAY_OF_MONTH) + " " + calendar.get(Calendar.YEAR);
lastclick.setText(getString(R.string.lastclick) + " " + theDate);
This shows the numbers of the month, day, and year, but there's got to be a better way of doing this? Isn't there some simple way of doing this like using PHP's date() function?
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("EEEE, MMMM d, yyyy 'at' h:mm a");
System.out.println(format.format(calendar.getTime()));
Running the above code outputs the current time (e.g., Saturday, May 26, 2012 at 11:03 PM).
See the Android documentation for SimpleDateFormat for more information.
The format specification of SimpleDateFormat is similar to that of PHP's date function:
echo date("l, M j, Y \a\\t g:i A");
You're right. Compared to the Java code, the PHP code is much more succinct.
Use the below to format the date as required. Refer this LINK
Calendar calendar = Calendar.getInstance();
lastclick.setText(getString(R.string.lastclick) + " " + String.format("%1$tA %1$tb %1$td %1$tY at %1$tI:%1$tM %1$Tp", calendar));
Where %1$tA for staurday,
%1$tb for May,
and so on...
This is actually a fairly subtle problem to get right, and I've not seen another answer here on SO that addresses both:
The Calendar's time zone (which means that it might be showing a different date than local)
The device's Locale (which affects the "right" way to format dates)
The previous answers to this question ignore locale, and other answers that involve conversion to a Date ignore the time zone. So here's a more complete, general solution:
Calendar cal = Calendar.getInstance(); // the value to be formatted
java.text.DateFormat formatter = java.text.DateFormat.getDateInstance(
java.text.DateFormat.LONG); // one of SHORT, MEDIUM, LONG, FULL, or DEFAULT
formatter.setTimeZone(cal.getTimeZone());
String formatted = formatter.format(cal.getTime());
Note that you need to use java.text.DateFormat here, not Android's own (confusingly-named) android.text.format.DateFormat.
Even simpler answer:
SimpleDateFormat.getDateTimeInstance().format(cal.getTime())
For me this works perfectly:
val cal = Calendar.getInstance()
val pattern = "EEEE, MMMM d, yyyy 'at' h:mm a"
val primaryLocale = getLocales(resources.configuration).get(0)
val dateFormat = SimpleDateFormat(dateFormatPattern, primaryLocale)
val formatedDate: String = dateFormat.format(cal.time)
I use this solution which is a mix of the other answers and also includes time
You can customize the DateFormat.SHORT parts to other constants to show more/different details
Short leads to this on my device: 17/07/2021 04:11
You can simply pass Calendar.getInstance() to get the current time
fun formatDateTime(calendar: Calendar):String{
val formatter = DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT)
formatter.timeZone = calendar.timeZone
return formatter.format(calendar.time)
}

Categories

Resources