date - 从字符串中获取日期并在Flutter Dart中转换为Date对象

标签 date flutter dart

我搜索了很多,但是找不到一个好的解决方案。
实际上,知道Java代码可以解决我的问题。但是我在Dart中尝试了不同的方法。
我的问题是我正在通过API获取时间表。我得到的答复是

05:30 (PTC)
13:10 (PTC)
17:20 (PTC)

我需要得到这个
5:30 AM
1:10 PM
5:20 PM

我用Java尝试和工作过的代码
     function tConvert (time) {
  time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];
  if (time.length > 1) { // If time format correct
    time = time.slice (1);  // Remove full string match value
    time[5] = +time[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
    time[0] = +time[0] % 12 || 12; // Adjust hours
  }
  return time.join (''); // return adjusted time or original string
}

//called as
$("#time").html(tConvert(time));

他的另一个问题
(PTC)有时会更改为其他代码,例如(BST)(IST)等。因此,仅替换(PTC不起作用)。

最佳答案

经过长时间的搜索,我解决了这些问题。所以我希望分享我的代码。
感谢@hiwa Jalal的帮助。

采取的步骤:

  • 使用RegEx删除了所有字符串String removeABC = removebrace2.replaceAll(RegExp(r'[a-zA-Z]'), '');
  • 删除具有类似regEx的空格和方括号。
  • 将我的结果转换为DateFormat
  •  DateTime gotFinalTime = intl.DateFormat('hh:mm').parse(removeABC);
                     String formattedTime = intl.DateFormat.jm().format(gotFinalTime);
    
                     print(formattedTime);
    
    

    这对我有用。谢谢

    关于date - 从字符串中获取日期并在Flutter Dart中转换为Date对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61382963/

    相关文章:

    Mysql:将日期从 'dd/mm/yyyy' 转换为 'yyyymmdd'

    右键单击 VSCode 时,Flutter::My Refactor 按钮不会出现

    dart - 聚合物 Dart @initMethod 未执行

    日期时间到日期的 Mysql 转换未反射(reflect)在输出中

    javascript - 如果 Date.now() 大于 Number.MAX_SAFE_INTEGER 会发生什么?

    flutter - Flutter:子 block 正在初始化,但是数据尚未存储在shared_preferences中

    android - 如何从 GridView 中删除内部滚动条?

    flutter - 屏幕弹出后弹出Flutter WebviewScaffold

    firebase - 尝试从Firestore获取数据时出错

    sql - 将数据从 Excel 移动到 SQL Server 表