Kotlin - Issue in getting milliseconds for Time passed - android

I have created below method to get the milliseconds from 12 hour format time :
fun getMillisecondsFromTime(time: String): String {
val formatter = SimpleDateFormat("hh aa")
formatter.isLenient = false
val oldDate = formatter.parse(getLocaleTime(time,"hh aa"))
val oldMillis = oldDate.time
return "" + oldMillis
}
I am calling this method as below for four different times:
var strTime1:String = DateUtils.getMillisecondsFromTime("1 PM")//13 * 3600
var strTime2:String = DateUtils.getMillisecondsFromTime("2 PM")//14 * 3600
var strTime3:String = DateUtils.getMillisecondsFromTime("1 AM")//1 * 3600
var strTime4:String = DateUtils.getMillisecondsFromTime("2 AM")//2 * 3600
Result am getting is wrong. i.e. for 1 PM milliseconds should be 48600 But, am getting :
1 PM >>>>>: 45000000, should be 48600
2 PM >>>>>: 48600000, should be 50400
What might be the issue?
EDIT : getting local time as below :
fun getLocaleTime(date: String, timeFormat: String): String {
val df = SimpleDateFormat(timeFormat, Locale.ENGLISH)
df.timeZone = TimeZone.getTimeZone("UTC")
val date = df.parse(date)
df.timeZone = TimeZone.getDefault()
val formattedDate = df.format(date)
return formattedDate
}

You need to get hours of the day using Calendar. And then multiply it with 3600. Like
fun getMillisecondsFromTime(time: String): String {
val formatter = SimpleDateFormat("hh aa")
formatter.isLenient = false
val oldDate = formatter.parse(getLocaleTime(time,"hh aa"))
// val oldMillis = oldDate.time
val cal = GregorianCalendar.getInstance()
cal.time = oldDate
val hourIn24Format = cal.get(Calendar.HOUR_OF_DAY)
return "" + (hourIn24Format * 3600)
}
Your current code is returning time in millies from milliseconds since January 1, 1970, 00:00:00 GMT to the time you gave as input.
Note:
I am not sure what you are trying to achieve in this way, but this seems not a good way. If you can explain more about your requirements, I or any other can guide you for better ways.

Related

Android Joda-Time with Kotlin

I am trying to create a function to check a given string time HH:mm is in range of another comparing to now.
Example: if the current hour is between 12:35 and 15:00 return true
But I always got false even if the current time is in range..
fun isTimeInRange(before: String, after: String): Boolean {
val now = DateTime.now()
val format = DateTimeFormat.forPattern("HH:mm")
return now >= DateTime.parse(before, format) && now <= DateTime.parse(after, format)
}
You need to do:
fun isTimeInRange(before: String, after: String): Boolean {
val now = DateTime.now()
val format = DateTimeFormat.forPattern("HH:mm")
return now.isAfter(DateTime.parse(before, format)) && now.isBefore(DateTime.parse(after, format))
}
Or use intervals.
You have to set before/after date to today's date. try this:
fun isTimeInRange(start: String, end: String): Boolean {
val now = DateTime.now()
val format = DateTimeFormat.forPattern("HH:mm")
val startTime: LocalTime = format.parseLocalTime(start)
val endTime: LocalTime = format.parseLocalTime(end)
val timeZone = DateTimeZone.getDefault()
val today: LocalDate = LocalDate.now(timeZone)
val startMoment: DateTime = today.toLocalDateTime(startTime).toDateTime(timeZone)
val endMoment: DateTime = today.toLocalDateTime(endTime).toDateTime(timeZone)
return now.isAfter(startMoment) && now.isBefore(endMoment)
}

UnsupportedTemporalTypeException: Unsupported field: HourOfDay in Kotlin

I would like to know the remaining d-day by calculating a specific date received from the server from the current date.
I wrote the code in the following way, but I got an error.
How cam I solve this problem?
val date = "2021-05-10T10:00:00.000Z"
val inputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH)
val outputFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH)
val formateDate : LocalDate = LocalDate.parse(date, inputFormatter)
val formattedDate = outputFormatter.format(formateDate)
val format = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val targetDate = format.parse(formattedDate)
val today = Calendar.getInstance()
val result = (today.time.time - targetDate.time) / (60 * 60 * 24 * 1000)
tv_remaining_date.text = "$result"

How to format in Kotlin date in string or timestamp to my preferred format?

I'm getting date data from weather API in two versions. The first one is just string like this: 2019-08-07 09:00:00 and like this: 1565209665. How do I change it to just the name of the day or day and month?
For example Monday, August.
I tried something like this in few configurations but it works only in full version. If I cat something then it throws an error:
var date = list.get(position).dt_txt
val formatter = DateTimeFormatterBuilder()
.appendPattern("yyyy-MM-dd HH:mm:ss").toFormatter()
formatter.parse(date)
First API format:
val firstApiFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val date = LocalDate.parse("2019-08-07 09:00:00" , firstApiFormat)
Log.d("parseTesting", date.dayOfWeek.toString()) // prints Wednesday
Log.d("parseTesting", date.month.toString()) // prints August
Second API format:
val secondApiFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
val timestamp = 1565209665.toLong() // timestamp in Long
val timestampAsDateString = java.time.format.DateTimeFormatter.ISO_INSTANT
.format(java.time.Instant.ofEpochSecond(timestamp))
Log.d("parseTesting", timestampAsDateString) // prints 2019-08-07T20:27:45Z
val date = LocalDate.parse(timestampAsDateString, secondApiFormat)
Log.d("parseTesting", date.dayOfWeek.toString()) // prints Wednesday
Log.d("parseTesting", date.month.toString()) // prints August
This is really simple
val dateFormated = SimpleDateFormat("dd/MM/yyyy").format(trans.created_date.toDate())
I hope this works for everybody, thanks to https://www.datetimeformatter.com/how-to-format-date-time-in-kotlin/
Try this code to get dayOfWeek and month name
Code
To String Date
Method
fun getAbbreviatedFromDateTime(dateTime: String, dateFormat: String, field: String): String? {
val input = SimpleDateFormat(dateFormat)
val output = SimpleDateFormat(field)
try {
val getAbbreviate = input.parse(dateTime) // parse input
return output.format(getAbbreviate) // format output
} catch (e: ParseException) {
e.printStackTrace()
}
return null
}
*How to use
val monthName=getAbbreviatedFromDateTime("2019-08-07 09:00:00","yyyy-MM-dd HH:mm:ss","MMMM")
println("monthName--"+monthName)
val dayOfWeek=getAbbreviatedFromDateTime("2019-08-07 09:00:00","yyyy-MM-dd HH:mm:ss","EEEE")
println("dayOfWeek--"+dayOfWeek)
To Timemillis
Methods
fun convertStringToCalendar( timeMillis: Long) {
//get calendar instance
val calendarDate = Calendar.getInstance()
calendarDate.timeInMillis = timeMillis
val month=getAbbreviatedFromDateTime(calendarDate,"MMMM");
val day=getAbbreviatedFromDateTime(calendarDate,"EEEE");
Log.d("parseTesting", month)// prints August
Log.d("parseTesting",day)// prints Wednesday
}
fun getAbbreviatedFromDateTime(dateTime: Calendar, field: String): String? {
val output = SimpleDateFormat(field)
try {
return output.format(dateTime.time) // format output
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
Use
val timestamp = "1565209665".toLong()
convertStringToCalendar(timestamp)
Try this
val stringDate="2019-08-07 09:00:00"
val dateFormat_yyyyMMddHHmmss = SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss", Locale.ENGLISH
)
val date = dateFormat_yyyyMMddHHmmss.parse(stringDate)
val calendar = Calendar.getInstance()
calendar.setTime(date)
val dayOfWeekString = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH)
Output:
dayOfWeekString : wednesday
val timeInMillis = 1565242471228
val calendar = Calendar.getInstance()
calendar.setTimeInMillis(timeInMillis)
val dayOfWeekString = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.ENGLISH)
val parsedDate: String? = if(monthOfYear < 10 && dayOfMonth > 10){
"${dayOfMonth}/0${monthOfYear + 1}/${year}"
} else if(dayOfMonth < 10 && monthOfYear > 10) {
"0${dayOfMonth}/${monthOfYear + 1}/${year}"
} else if(dayOfMonth < 10 && monthOfYear < 10){
"0${dayOfMonth}/0${monthOfYear + 1}/${year}"
}else{
"0${dayOfMonth}/${monthOfYear + 1}/${year}"
}
date?.text = parsedDate
I tried different things but in Date picker this works for me in kotlin

How do I convert a Firestore date/Timestamp to Date in Kotlin?

i'm working with firestore, and getting stuck when i get the timestamp from firestore. how i convert this Timestamp(seconds=1556006384, nanoseconds=994000000) to Date in kotlin.
my minimum SDK is 21 so the code below doesn't work
val timestamp = it["time"] as com.google.firebase.Timestamp
val milliseconds = timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000
val tz = ZoneId.of("Asia/Jakarta (UTC+07:00)")
val localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(milliseconds), tz)
thank you.
Call toDate() on a Firestore Timestamp object to return a Date object.
I'm using this code:
val timestamp = it["time"] as com.google.firebase.Timestamp
val milliseconds = timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000
val sdf = SimpleDateFormat("MM/dd/yyyy")
val netDate = Date(milliseconds)
val date = sdf.format(netDate).toString()
Log.d("TAG170", date)
Combined both answers on top and this is what worked for me.
val timestamp = data[TIMESTAMP] as com.google.firebase.Timestamp
val date = timestamp.toDate()
I used this class to serialize the Timestamp
import com.google.firebase.Timestamp
data class Article (
var createdAt: Timestamp? = Timestamp.now(),
var title: String = "",
var image: String = ""
)

How to get current local date and time in Kotlin

How to get current Date (day month and year) and time (hour, minutes and seconds) all in local time in Kotlin?
I tried through LocalDateTime.now() but it is giving me an error saying Call requires API Level 26 (curr min is 21).
How could I get time and date in Kotlin?
Try this :
val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
val currentDate = sdf.format(Date())
System.out.println(" C DATE is "+currentDate)
My utils method for get current date time using Calendar when our minSdkVersion < 26.
fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
val formatter = SimpleDateFormat(format, locale)
return formatter.format(this)
}
fun getCurrentDateTime(): Date {
return Calendar.getInstance().time
}
Using
import ...getCurrentDateTime
import ...toString
...
...
val date = getCurrentDateTime()
val dateInString = date.toString("yyyy/MM/dd HH:mm:ss")
java.util.Calendar.getInstance() represents the current time using the current locale and timezone.
You could also choose to import and use Joda-Time or one of the forks for Android.
You can get current year, month, day etc from a calendar instance
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)
val day = c.get(Calendar.DAY_OF_MONTH)
val hour = c.get(Calendar.HOUR_OF_DAY)
val minute = c.get(Calendar.MINUTE)
If you need it as a LocalDateTime, simply create it by using the parameters you got above
val myLdt = LocalDateTime.of(year, month, day, ... )
Try this:
val date = Calendar.getInstance().time
val formatter = SimpleDateFormat.getDateTimeInstance() //or use getDateInstance()
val formatedDate = formatter.format(date)
You can use your own pattern as well, e.g.
val sdf = SimpleDateFormat("yyyy.MM.dd")
// 2020.02.02
To get local formatting use getDateInstance(), getDateTimeInstance(), or getTimeInstance(), or use new SimpleDateFormat(String template, Locale locale) with for example Locale.US for ASCII dates.
The first three options require API level 29.
To get the current Date in Kotlin do this:
val dateNow = Calendar.getInstance().time
fun main(){
println(LocalDateTime.now().toString()) //2021-10-25T12:03:04.524
println(Calendar.getInstance().time) //Mon Oct 25 12:02:23 GST 2021
}
There are the above options, with the output added as comment.
You can use this function
fun getCurrentDate():String{
val sdf = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS")
return sdf.format(Date())
}
fun now(): String {
return SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())
}
val currentYear = SimpleDateFormat("yyyy",Locale.getDefault()).format(Date())
val currentMonth = SimpleDateFormat("MM",Locale.getDefault()).format(Date())
val currentDay = SimpleDateFormat("dd",Locale.getDefault()).format(Date())
checkout these easy to use Kotlin extensions for date format
fun String.getStringDate(initialFormat: String, requiredFormat: String, locale: Locale = Locale.getDefault()): String {
return this.toDate(initialFormat, locale).toString(requiredFormat, locale)
}
fun String.toDate(format: String, locale: Locale = Locale.getDefault()): Date = SimpleDateFormat(format, locale).parse(this)
fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
val formatter = SimpleDateFormat(format, locale)
return formatter.format(this)
}
Assuming that we got time in seconds we can do something like: (koltin language)
val dateObject = Date(timeInMillis)
val calendarInstance = Calendar.getInstance()
calendarInstance.time = dateObject
val hour = calendarInstance.get(Calendar.HOUR)
val minute = calendarInstance.get(Calendar.MINUTE)
val ampm = if(calendarInstance.get(Calendar.AM_PM)==0) "AM " else "PM "
val date = calendarInstance.get(Calendar.DATE)
val month = calendarInstance.get(Calendar.MONTH)
val year = calendarInstance.get(Calendar.YEAR)
I use this to fetch data from API every 20 seconds
private fun isFetchNeeded(savedAt: Long): Boolean {
return savedAt + 20000 < System.currentTimeMillis()
}
Another solution is changing the api level of your project in build.gradle and this will work.

Categories

Resources