android - 如何在 Kotlin 中将字符串转换为特定格式?
问题描述
在普通语言中,如 C#,它很简单:
long test = 110119225603;
string dateFormat = test.ToString("##:##:## ##:##:##");
Console.WriteLine(dateFormat); // 11:01:19 22:56:03
那么,如何在 Kotlin 中做到这一点?
解决方案
您可以利用在 Kotlin 中扩展现有类的可能性并编写一个小的扩展函数来满足您的需求:
// extend Long with a suitable function
fun Long.toFormattedString(format: String): String {
// get the Long as String in order to be able to iterate it
val s = this.toString()
// provide a variable for the index
var i = 0
// create an empty result String
var sb: String = ""
// go through the pattern String
for (c in format) {
// replace # with the current cipher
if (c == '#') {
sb += s.get(i)
// increment the counter
i++
} else {
// for every other char in the pattern, just add that char
sb += c
}
}
return sb
}
// try it in a main function
fun main() {
// provide an input and a pattern
val l: Long = 110119225603
val p = "##:##:## ##:##:##"
// print the result of the extension function
print(l.toFormattedString(p))
}
这输出
11:01:19 22:56:03
推荐阅读
- node.js - Azure 管道和 yaml:如何在多个文件夹下处理文件?
- azure - API 管理用例
- cmake - 命令调用中的 CMake 参数可以以行注释结尾
- r - 根据其他列的 10 个最高数字选择 10 个名称
- react-select - 我怎样才能有一个可搜索的 ReactSelect 组件,它根据输入值显示/切换值?
- java - 在java中创建线程池并创建退出信号
- mysql - 设置日、日、时、分、秒间隔
- python - 在 xlabels 上绘制带有总行和日期的堆叠条形图
- android - AndroidStudio ConstrainLayout 不起作用
- c# - c#锁定实时数据收集/聚合中的空值异常