Flutter缩短字符串

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

Flutter shorten a string

问题

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

结果:

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

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

Result:

  1. String? time = "14:50";

I tried to try with regex but failed

答案1

得分: 2

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

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

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

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

答案2

得分: 0

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

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:

确定