I am trying to convert a timestamp to a day of the week.
The goal would be to translate to something like ts -> MON or TUE ....
I have tried the code below but it's not working.
fun convertToReadableDate(timestamp: Long): String {
val formatter = SimpleDateFormat("dd-mm-yyyy")
val cal = Calendar.getInstance(Locale.ENGLISH)
cal.timeInMillis = timestamp * 1000
val date: LocalDate = LocalDate.parse(formatter.format(cal.time))
return date.dayOfWeek.toString()
}
Any idea ?
Thanks
get the day of the week from Unix timestamp:-
fun getDayOfWeek(timestamp: Long): String {
return SimpleDateFormat("EEEE", Locale.ENGLISH).format(timestamp * 1000)
}
getMonth:
fun getMonthFromTimeStamp(timestamp: Long): String {
return SimpleDateFormat("MMM", Locale.ENGLISH).format(timestamp * 1000)
}
getYear:
fun getYearFromTimeStamp(timestamp: Long): String {
return SimpleDateFormat("yyyy", Locale.ENGLISH).format(timestamp * 1000)
}
if you need all three combined in one function: (WED-MAY-2021)
fun getDayOfWeek(timestamp: Long): String {
return SimpleDateFormat("EEEE-MMM-yyyy", Locale.ENGLISH).format(timestamp * 1000)
}
if you need a combination of either of two in one function:(WED-MAY)
fun getDayOfWeek(timestamp: Long): String {
return SimpleDateFormat("EEEE-MMM", Locale.ENGLISH).format(timestamp * 1000)
}
You can use this formatter:
fun convertToReadableDate(timestamp: Long): String =
SimpleDateFormat("EEE", Locale.ENGLISH).format(timestamp)
.toUpperCase(Locale.ENGLISH)
Related
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)
}
I came across a strange bug and I can't figure out why it occurs. If I invoke my original function, roundToMidnight() is not called and the date is not rounded.
My original function, what doesn't work:
suspend operator fun invoke(reference: Reference) = reference.tagId
?.let { tagRepository.getTag(it) }
?.uploadDate ?: Date()
.apply { time += accountRepository.getAccount().first().defaultExpiryPeriod }
.roundToMidnight()
}
What does work:
suspend operator fun invoke(reference: Reference): Date {
val date = reference.tagId
?.let { tagRepository.getTag(it) }
?.uploadDate ?: Date()
.apply { time += accountRepository.getAccount().first().defaultExpiryPeriod }
return date.roundToMidnight()
}
roundToMidnight() returns a new instance of Date
fun Date.roundToMidnight(): Date {
val calendar = Calendar.getInstance()
calendar.time = this
calendar[Calendar.HOUR_OF_DAY] = 23
calendar[Calendar.MINUTE] = 59
calendar[Calendar.SECOND] = 59
calendar[Calendar.MILLISECOND] = 0
return Date(calendar.timeInMillis)
}
What causes the differences in both functions? I'd say they would be exactly the same and I see myself refactoring the bugless function into the original in a month time, because I forgot this happens.
As suggested by Egor, an expression body is not always the best solution. Rewrote it to this.
suspend operator fun invoke(reference: Reference): Date {
val tag = reference.tagId?.let { tagRepository.getTag(it)}
val uploadDateOrNow = tag?.uploadDate ?: Date()
uploadDateOrNow.time += defaultExpiryPeriod()
return uploadDateOrNow.roundToMidnight()
}
private suspend fun defaultExpiryPeriod() = accountRepository
.getAccount().first()
.defaultExpiryPeriod
Working on a project of my own and boy, do I miss being criticized in PRs ones in a while.
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.
l am try to convert timeestamp coming from data json url
TimeFlight.text = list[position].TimeFlight.getDateTime(toString())
l am use list view in my app
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view : View = LayoutInflater.from(context).inflate(R.layout.row_layout,parent,false)
val TimeFlight = view.findViewById(R.id.time_id) as AppCompatTextView
val LogoAriline = view.findViewById(R.id.logo_image) as ImageView
status.text= list[position].Stauts
TimeFlight.text = list[position].TimeFlight.getDateTime(toString())
Picasso.get().load(Uri.parse("https://www.xxxxxxxxx.com/static/images/data/operators/"+status.text.toString()+"_logo0.png"))
.into(LogoAriline)
return view as View
}
private fun getDateTime(s: String): String? {
try {
val sdf = SimpleDateFormat("MM/dd/yyyy")
val netDate = Date(Long.parseLong(s))
return sdf.format(netDate)
} catch (e: Exception) {
return e.toString()
}
}
Data class for json
data class FlightShdu (val Airline : String ,val TimeFlight : String)
l used that code getDateTime but the format unknown
Assuming TimeFlight is a stringified epoch timestamp (in milliseconds), you should pass that to your getDateTime() function:
TimeFlight.text = getDateTime(list[position].TimeFlight)
(if they are not millis but seconds, then simply multiply them by 1000 before passing them to the Date constructor)
On a side note, depending on the exact use case, creating a new SimpleDateFormat object might not be necessary on every getDateTime() call, you can make it an instance variable.
Also, i'd advise you to take a look at (and follow) the Java naming conventions for both Java and Kotlin applications.
The problem here is that the Date constructor take long as the milliseconds count since 1/1/1970 and the number you are getting is the seconds count.
my suggestion is the following code( you can change the formate):
const val DayInMilliSec = 86400000
private fun getDateTime(s: String): String? {
return try {
val sdf = SimpleDateFormat("MM/dd/yyyy")
val netDate = Date(s.toLong() * 1000 ).addDays(1)
sdf.format(netDate)
} catch (e: Exception) {
e.toString()
}
}
fun Date.addDays(numberOfDaysToAdd: Int): Date{
return Date(this.time + numberOfDaysToAdd * DayInMilliSec)
}
private fun getDateTime(s: String): String? {
return try {
val date = SimpleDateFormat("MM/dd/yyyy HH:mm:ss").format(Date(s.toLong()*1000))
// current timestamp in sec
val epoch = System.currentTimeMillis()/1000
// Difference between two epoc
val dif = epoch - s.toLong()
val timeDif: String
when {
dif<60 -> {
timeDif = "$dif sec ago"
}
dif/60 < 60 -> {
timeDif = "${dif/60} min ago"
}
dif/3600 < 24 -> {
timeDif = "${dif/3600} hour ago"
}
dif/86400 < 360 -> {
timeDif = "${dif/86400} day ago"
}
else ->{
timeDif = "${dif/31556926} year ago"
}
}
"($timeDif) $date"
} catch (e: Exception) {
e.toString()
}
}
The Code A can convert a long value to date value, just like 2018.01.10
I hope to get Date + Time value , such as 2018.01.10 23:11, how can I do with Kotlin?
I hope to convert current time to a long value , how can I do with Kotlin?
Thanks!
Code A
fun Long.toDateString(dateFormat: Int = DateFormat.MEDIUM): String {
val df = DateFormat.getDateInstance(dateFormat, Locale.getDefault())
return df.format(this)
}
Try this, I use SimpleDataFormat.
fun convertLongToTime(time: Long): String {
val date = Date(time)
val format = SimpleDateFormat("yyyy.MM.dd HH:mm")
return format.format(date)
}
fun currentTimeToLong(): Long {
return System.currentTimeMillis()
}
fun convertDateToLong(date: String): Long {
val df = SimpleDateFormat("yyyy.MM.dd HH:mm")
return df.parse(date).time
}
And to convert java file to kotlin file with Android Studio, choosing Code->Convert java file to kotlin file.
No need for anything complex:
Get current time and date as a Date object
val dateTime: Date = Calendar.getInstance().time
Convert it to a Long
val dateTimeAsLong: Long = dateTime.time
Convert that Long back to a Date
val backToDate: Date = Date(dateTimeAsLong)
I like to use extension functions, as so...
Convert long to Time & Date String:
fun Long.toTimeDateString(): String {
val dateTime = java.util.Date(this)
val format = SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US)
return format.format(dateTime)
}
Convert Time & Date String to Long:
fun String.toTimeDateLong(): Long {
val format = SimpleDateFormat("HH:mm:ss dd/MM/yyyy", Locale.US)
return format.parse(this)?.time ?: throw IllegalArgumentException("Invalid time string")
}
To use:
fun main() {
val timeDateLong = "10:23:12 12/11/2022".toTimeDateLong()
val timeDateStr = timeDateLong.toTimeDateString()
}