- Kotlin конвертировать TimeStamp в DateTime
- 13 ответов
- Date from timestamp kotlin
- How to format in kotlin date in string or timestamp to my preferred format?
- Method 1: SimpleDateFormat Class
- Method 2: Using the DateTimeFormatter Class
- Method 3: Using the Date class
- Method 4: Using the Calendar class
- How To Format Date in Kotlin — All in One Solution
- Usage: Time Stamp To Simple String Date Format
- An explanation for other Date Formats
- Year:
- Month:
- Day:
Kotlin конвертировать TimeStamp в DateTime
Есть ли какое-то решение для этого в kotlin или я должен использовать синтаксис Java в kotlin? Пожалуйста, дайте мне простой пример, чтобы показать, как я могу решить эту проблему. Заранее спасибо.
эта ссылка не является ответом на мой вопрос
13 ответов
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() >>
Это на самом деле так же, как Java. Попробуй это:
val stamp = Timestamp(System.currentTimeMillis()) val date = Date(stamp.getTime()) println(date)
class DateTest < private val simpleDateFormat = SimpleDateFormat("dd MMMM yyyy, HH:mm:ss", Locale.ENGLISH) @Test fun testDate() < val time = 1560507488 println(getDateString(time)) // 14 June 2019, 13:18:08 >private fun getDateString(time: Long) : String = simpleDateFormat.format(time * 1000L) private fun getDateString(time: Int) : String = simpleDateFormat.format(time * 1000L) >
Обратите внимание, что мы умножаем на 1000L, а не на 1000. Если у вас есть целое число (1560507488), умноженное на 1000, вы получите неправильный результат: 17 января 1970 г., 17:25:59.
Хотя это Kotlin, вы все равно должны использовать Java API. Пример преобразования API в API Java 8+ 1510500494 который вы упомянули в комментариях к вопросу:
import java.time.* val dt = Instant.ofEpochSecond(1510500494).atZone(ZoneId.systemDefault()).toLocalDateTime()
Date from timestamp kotlin
Kotlin is a cross-platform, statically typed, general-purpose programming language with type inference. It is a modern programming language that makes developers happier. It provides many date time functions to handle date time functionality.
Here we will explain Kotlin date time functions to get current epoch or Unix timestamp, convert timestamp to date and convert date to epoch or Unix timestamp.
- Epoch and Date Time Conversion in PHP
- Epoch and Date Time Conversion in JavaScript
- Epoch and Date Time Conversion in Perl
- Epoch and Date Time Conversion in Python
- Epoch and Date Time Conversion in Go
- Epoch and Date Time Conversion in Java
- Epoch and Date Time Conversion in Ruby
- Epoch and Date Time Conversion in MySQL
- Epoch and Date Time Conversion in SQL Server
- Epoch and Date Time Conversion in TypeScript
- Epoch and Date Time Conversion in VBA
- Epoch and Date Time Conversion in Rust
- Epoch and Date Time Conversion in Matlab
You can get the current unix timestamp using currentTimeMillis() .
Convert epoch or Unix timestamp to date in Kotlin
You can convert unix timestamp to date as follows.
val timeStamp = Timestamp(System.currentTimeMillis()) val date = Date(timeStamp.getTime())
Convert date to epoch or unix timestamp in Kotlin
You can convert the date to unix timestamp using following.
val date = SimpleDateFormat(«dd-MM-yyyy»).parse(«04-07-2021») println(date.time)
How to format in kotlin date in string or timestamp to my preferred format?
Formatting a date in Android can be a complex task, especially when working with different time zones and locales. In Kotlin, you can use the SimpleDateFormat class to format a date and time into a string representation, or parse a string into a Date object. The SimpleDateFormat class provides a variety of patterns that you can use to format the date and time, but it can be challenging to get the formatting just right. This tutorial will guide you through the process of formatting a date in Kotlin and provide you with solutions to some common problems you may encounter along the way.
Method 1: SimpleDateFormat Class
To format a date in Kotlin using the SimpleDateFormat class, you can follow these steps:
- Create an instance of SimpleDateFormat class by passing your desired date format as a string to the constructor.
val dateFormat = SimpleDateFormat("dd/MM/yyyy")
val date = Date() // current date and time
- Call the format() method on your SimpleDateFormat object, passing in your Date object as a parameter.
val formattedDate = dateFormat.format(date)
Here are some additional examples:
// Format a timestamp to a string date val timestamp = 1629360000000 // 2021-08-19T00:00:00Z val date = Date(timestamp) val dateFormat = SimpleDateFormat("dd/MM/yyyy") val formattedDate = dateFormat.format(date) // "19/08/2021" // Format a string date to a different format val dateString = "19/08/2021" val dateFormat = SimpleDateFormat("dd/MM/yyyy") val date = dateFormat.parse(dateString) val newDateFormat = SimpleDateFormat("yyyy-MM-dd") val formattedDate = newDateFormat.format(date) // "2021-08-19"
That’s it! With these steps, you can easily format dates in Kotlin using the SimpleDateFormat class.
Method 2: Using the DateTimeFormatter Class
To format a date in Kotlin using the DateTimeFormatter class, you can follow these steps:
- Create a LocalDateTime object with the desired date and time.
- Define the pattern for the date format you want to use.
- Create a DateTimeFormatter object using the pattern.
- Format the LocalDateTime object using the DateTimeFormatter object.
Here is an example code that formats a date in the format «dd/MM/yyyy HH:mm:ss»:
import java.time.LocalDateTime import java.time.format.DateTimeFormatter fun formatDate(date: LocalDateTime): String val pattern = "dd/MM/yyyy HH:mm:ss" val formatter = DateTimeFormatter.ofPattern(pattern) return date.format(formatter) > // Example usage val now = LocalDateTime.now() val formattedDate = formatDate(now) println(formattedDate) // Output: "25/08/2021 14:30:45"
In the above code, the formatDate function takes a LocalDateTime object as input and returns a formatted string using the DateTimeFormatter class.
You can customize the date format by changing the pattern variable to your desired format. For example, to format the date as «yyyy-MM-dd», you can change the pattern to «yyyy-MM-dd» .
Method 3: Using the Date class
To format a date in Kotlin using the Date class, you can use the SimpleDateFormat class. Here’s an example:
import java.text.SimpleDateFormat import java.util.Date fun formatDate(date: Date, format: String): String val formatter = SimpleDateFormat(format) return formatter.format(date) > // Usage: val date = Date() val formattedDate = formatDate(date, "dd/MM/yyyy") println(formattedDate) // Output: 12/09/2021
In the example above, we define a function formatDate that takes a Date object and a format string as arguments, and returns a formatted date string. The SimpleDateFormat class is used to format the date according to the specified format.
The format string can contain various placeholders to represent different parts of the date, such as dd for day of the month, MM for month, yyyy for year, HH for hour, mm for minute, ss for second, and so on.
Here are some examples of format strings and their corresponding output:
val date = Date() formatDate(date, "dd/MM/yyyy") // Output: 12/09/2021 formatDate(date, "yyyy-MM-dd") // Output: 2021-09-12 formatDate(date, "EEE, MMM d, ''yy") // Output: Sun, Sep 12, '21 formatDate(date, "h:mm a") // Output: 10:30 PM
Note that the SimpleDateFormat class is not thread-safe, so it’s recommended to create a new instance for each thread or synchronize access to a shared instance.
Method 4: Using the Calendar class
To format a date in Kotlin using the Calendar class, you can follow these steps:
val calendar = Calendar.getInstance() calendar.timeInMillis = timestampInMillis
val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault())
val formattedDate = dateFormat.format(calendar.time)
Here is the complete code example:
val calendar = Calendar.getInstance() calendar.timeInMillis = timestampInMillis val dateFormat = SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.getDefault()) val formattedDate = dateFormat.format(calendar.time)
In this example, timestampInMillis is the timestamp in milliseconds that you want to format. The dateFormat variable defines the format of the output date, which in this case is «dd/MM/yyyy HH:mm:ss». The Locale.getDefault() method is used to get the default locale of the device.
This code will output the formatted date as a string in the format «dd/MM/yyyy HH:mm:ss».
Note that the Calendar class is a bit outdated and there are newer and more efficient ways to format dates in Kotlin, such as using the Java 8 DateTime API or the Kotlin DateTime library.
How To Format Date in Kotlin — All in One Solution
Are you worrying? How to format timestamp to String date? here you can find the complete solution in one place.
Here we have created a generic Method that you can use where ever you require.
public fun getDateFormattedFromTimeStamp(timestamp: Long, format: String): String
Usage: Time Stamp To Simple String Date Format
getDateFormattedFromTimeStamp(Calendar.getInstance().timeInMillis, "yyyy, MMM dd") output: // 2022, Sep 03
An explanation for other Date Formats
Year:
“ yyyy ” → 4-digit Year (eg. 2022 )
“ yy ” → 2-digit Year (eg. 22 )
Month:
“ MM ” → 2-digit Month (eg. 01 )
“ MMM ” → 3- character Month (eg. Jan )
“ MMMM ” → Full characters Month (eg. January )
Day:
“ dd ” or “ d ” → Day in a month (eg. 19 )
“ DD ” or “ D ” → Day in Year (eg. 262 )
val timestamp = 1663584353488 DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy-MMM-dd") // 2022-Sep-19 DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy, MMM dd") // 2022, Sep 19 DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy/MMM/dd") // 2022/Sep/19 DateUtil.getDateFormattedFromTimeStamp(timestamp, "yyyy/MM/dd") // 2022/09/19 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMM, yy") // 19 Sep, 22 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd, MMM yy") // 19, Sep 22 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd, MMM yyyy") // 19, Sep 2022 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMM, yyyy") // 19 Sep, 2022 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MM, yyyy") // 19 09, 2022 DateUtil.getDateFormattedFromTimeStamp(timestamp, "DD MM, yyyy") // 262 09, 2022 DateUtil.getDateFormattedFromTimeStamp(timestamp, "dd MMMM, yyyy") // 19 September, 2022