How to format Firestore server timestamp in kotlin? - android

After I retrieve the date of data field from Firestore's Timestamp. I want to format my Timestamp date to "dd MMM yyyy, HH:mm" in my recyclerview. I tried to use DateTimeFormatter but it doesn't works.
override fun onBindViewHolder(holder: OrderListViewHolder, position: Int) {
val item = orderList[position]
orderViewModel.setOrderProduct(item.foodItem)
orderViewModel.setStatus(item.status)
val foodItem = item.foodItem?.map { it.itemName }
val date = Date(item.date!!.toDate().time)
val newDate = date.toString().substring(0, 16) + date.toString().substring(29, 34)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = newDate.format(formatter)
Log.d("dates", "${formattedDate}")
holder.orderDate.text = formattedDate
holder.foodName.text = foodItem.toString().removeSurrounding("[", "]")
holder.status.text = orderViewModel.status.value.toString()
}
Currently, I only know how to use substring to design my date format. But it's not my expected.
How can I set my Timestamp format?

fun getDateString(seconds: Long, outputPattern: String): String {
try {
val dateFormat = SimpleDateFormat(outputPattern, Locale.ENGLISH)
val calendar = Calendar.getInstance()
calendar.timeInMillis = seconds * 1000
val date = calendar.time
return dateFormat.format(date)
} catch (e: Exception) {
Log.e("utils", "Date format", e)
return ""
}
}

With this code:
val date = Date(item.date!!.toDate().time)
val newDate = date.toString().substring(0, 16) + date.toString().substring(29, 34)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = newDate.format(formatter)
you are taking a date from an item, creating a Date object, then you're adding some string manipulation. Note that toString() on a date could generate different results, based on the system preferences. This is already something you should avoid.
Then you're creating a DateTimeFormatter and using it on the newDate, that is a String, so it will not do what you are expecting.
You can obtain what you want simply by using the format on the date and not on the string:
val date = Date(item.date!!.toDate().time)
val formatter = DateTimeFormatter.ofPattern("dd MMM yyyy, HH:mm")
val formattedDate = date.format(formatter)

Related

How to generate dates of between 2 dates in Android

In my application I want get dates between 2 date and for this I write below codes.
But when show current date miss today!
For example today is 2022-07-31 but show me 2022-07-30!
My code is :
private fun getDatesBetween(): MutableList<String> {
val dates = ArrayList<String>()
val input = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
var date1: Date? = null
var date2: Date? = null
val sdf = SimpleDateFormat("yyyy-MM-dd")
val currentDate = sdf.format(Date())
try {
date1 = input.parse("2020-1-1")
date2 = input.parse(currentDate)
} catch (e: ParseException) {
e.printStackTrace()
}
val cal1 = Calendar.getInstance()
cal1.time = date1
val cal2 = Calendar.getInstance()
cal2.time = date2
while (!cal1.after(cal2)) {
val output = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
dates.add(output.format(cal1.time))
cal1.add(Calendar.DATE, 1)
}
return dates
}
I think this problem for this line :
cal1.add(Calendar.DATE, 1)
How can I fix it?
How can I fix it?
I didn't test it, but I think that works:
add this little helper function:
private fun getDayDiff(lowerValue: Long, higherValue: Long): Int {
val diffMillis = higherValue.minus(lowerValue)
val cal = Calendar.getInstance()
cal.timeInMillis = diffMillis
return cal.get(Calendar.DAY_OF_YEAR)
}
and instead of your while loop:
repeat(getDayDiff(cal1.timeInMillis, cal2.timeInMillis)){
cal1.add(Calendar.DATE,1)
val output = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
dates.add(output.format(cal1.time))
}

How to convert API date to string in Kotlin within my recyclerview adapter?

I need to convert API date from this (yyyy-MM-dd HH:mm:ss) format to (oct 18) like this
#Throws(ParseException::class)
private fun getFormate(date: String): String? {
val d: Date = SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.ENGLISH).parse(date)
//Log.d("Date", String.valueOf(d));
val cal = Calendar.getInstance()
cal.time = d
return SimpleDateFormat("MMM dd").format(cal.time)
}
inside of onBindViewHolder
val thisModelResponse: ExpiryData = expiryList.get(position)
holder.expiryDate1.text = getFormate(thisModelResponse.getCreatedDate())
holder.expiryDate1.text = (expiryItem.expiryDate)
But i'm getting error unresolved refference in getCreatedDate()
To convert date from string, returning a new parsed date you must do:
val inputDate = "2018-10-18 11:00:00"
val inputDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
val outputDate = inputDateFormat.parse(inputDate)
val outputDateFormat = SimpleDateFormat("MMM dd")
val result : String = outputDateFormat.format(outputDate)
result will be "Oct 18"

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 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.

How can i get current date and time in android and store it into string

Currently i am using the code below:
String currentDateTimeString = DateFormat.getDateTimeInstance()
.format(new Date());
From this i am getting the output in the following format -
Jun 5, 2015 1:15:29 PM
But now i want the output in the format below-
2015-06-05 08:10:40
It can be in 12 or 24 hour format.
I want current date time with above datetime format.
I have already use SimpleDateFormat but i am not able to get the above
date time format with current date and time
So, how can i achieve this?
Update 01/Sept/2020 - Sample Kotlin DateUtilExtensions using Java SE 8
#file:JvmName("DateUtilExtensions")
package com.intigral.jawwytv.util.extensions
import android.text.TextUtils
import android.text.format.DateUtils
import java.text.ParseException
import java.text.SimpleDateFormat
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.util.Date
import java.util.Locale
import java.util.TimeZone
const val PATTERN_YEAR = "yyyy"
const val PATTERN_MONTH = "MMM"
const val PATTERN_MONTH_FULL = "MMMM"
const val PATTERN_DAY_OF_MONTH = "dd"
const val PATTERN_DAY_OF_WEEK = "EEEE"
const val PATTERN_TIME = "hh:mm a"
const val PATTERN_TIME_24H = "HH:mm"
const val PATTERN_SERVER_DATE = "yyyy-MM-dd"
const val PATTERN_SERVER_DATE_TIME = "yyyy-MM-dd HH:mm:ss"
const val PATTERN_START_WITH_MONTH = "MMM dd , yyyy"
const val PATTERN_START_WITH_MONTH_NO_YEAR = "MMMM dd"
const val PATTERN_START_WITH_DATE_NO_YEAR = "dd MMMM"
const val PATTERN_START_WITH_MONTH_SHORT_NO_YEAR = "MMM dd"
const val PATTERN_START_WITH_MONTH_WITH_TIME = "MMM dd, yyyy HH:mm:ss"
const val PATTERN_START_WITH_MONTH_SMALL_NO_YEAR = "MMM dd"
fun formatDate(pattern: String): String {
val localDateTime = LocalDateTime.now()
return localDateTime.format(DateTimeFormatter.ofPattern(pattern))
}
fun formatDate(localDateTime: LocalDateTime, pattern: String): String =
localDateTime.format(DateTimeFormatter.ofPattern(pattern))
fun formatDate(timeInMills: Long?, pattern: String): String =
LocalDateTime.ofInstant(Instant.ofEpochMilli(timeInMills ?: 0), ZoneId.systemDefault())
.format(DateTimeFormatter.ofPattern(pattern))
fun todayToEpochMilli() =
LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli()
fun isDateEqual(dateInMills: Long?, dateInMillsOther: Long?): Boolean {
val systemDefault = ZoneOffset.systemDefault()
val date = Instant.ofEpochMilli(dateInMills ?: 0).atZone(systemDefault).toLocalDate()
val otherDate =
Instant.ofEpochMilli(dateInMillsOther ?: 0).atZone(systemDefault).toLocalDate()
return date.isEqual(otherDate)
}
fun convertDateString(inputPattern: String, outputPattern: String, stringDate: String): String? {
val originalFormat = SimpleDateFormat(inputPattern, Locale.getDefault())
val targetFormat = SimpleDateFormat(outputPattern, Locale.getDefault())
val requiredFormat = originalFormat.parse(stringDate)
return requiredFormat?.let { targetFormat.format(requiredFormat) }
}
fun getRelativeTimeSpanString(
dateString: String,
format: String = PATTERN_SERVER_DATE_TIME
): String? {
if (!TextUtils.isEmpty(dateString)) {
val simpleDateFormat = SimpleDateFormat(format, Locale.getDefault())
simpleDateFormat.timeZone = TimeZone.getTimeZone(ZoneOffset.UTC)
var date: Date? = null
try {
date = simpleDateFormat.parse(dateString)
} catch (e: ParseException) {
e.printStackTrace()
}
val epochTime = date!!.time
val relTime = DateUtils.getRelativeTimeSpanString(
epochTime,
System.currentTimeMillis(),
DateUtils.SECOND_IN_MILLIS
)
return relTime.toString()
}
return dateString
}
Initial Answer - use SimpleDateFormat
Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");
String dateToStr = format.format(today);
System.out.println(dateToStr);
Solution by simpledate formator:
Date todaysdate = new Date();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String date = format.format(todaysdate);
System.out.println(date);
Use this method
public static String currentDate() {
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
// get current date time with Date()
Date date = new Date();
// System.out.println(dateFormat.format(date));
// don't print it, but save it!
return dateFormat.format(date);
}
Change the Date time formate according to your
Simply get it as,
SimpleDateFormat.getDateTimeInstance().format(new Date());
Instead of getDateTimeInstance, you can also use
getDateInstance() and
getTimeInstance().

Categories

Resources