Flutter缩短字符串

huangapple go评论62阅读模式
英文:

Flutter shorten a string

问题

String? time = "2023-02-21 14:50:40";

结果:

String? time = "14:50";

我尝试使用正则表达式但失败了。

英文:

I have a string showing the date and time, but I only want to see the hour and minute. how do i do this with flutter.Sorry if there are other questions that I missed.

String? time = "2023-02-21 14:50:40";

Result:

String? time = "14:50";

I tried to try with regex but failed

答案1

得分: 2

我认为最快的方法是使用内置的 DateTime.parse()

final dt = DateTime.parse('2023-02-21 14:50:40');
final result = '${dt.hour}:${dt.minute}';
英文:

I think the quickest way is using the built-in DateTime.parse():

  final dt = DateTime.parse('2023-02-21 14:50:40');
  final result = '${dt.hour}:${dt.minute}';

答案2

得分: 0

    import 'package:intl/intl.dart';
    void main() {
        String? time = "2023-02-21 14:50:40";
        DateTime tempDate =  DateFormat("yyyy-MM-dd hh:mm:ss").parse(time);
        String? hourTime = tempDate.hour.toString();
        String? minuteTime = tempDate.minute.toString();
        print(hourTime); //14
        print(minuteTime); //50
    }
英文:
import 'package:intl/intl.dart';
void main() {
String? time = "2023-02-21 14:50:40";
DateTime tempDate =  DateFormat("yyyy-MM-dd hh:mm:ss").parse(time);
String? hourTime = tempDate.hour.toString();
String? minuteTime = tempDate.minute.toString();
print(hourTime); //14
print(minuteTime); //50
}

You can use intl package for convert string to datetime.

huangapple
  • 本文由 发表于 2023年2月24日 17:02:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75554522.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定