如何仅从DateTime.now()中提取时间;

时间:2019-06-03 12:29:46

标签: flutter dart

我有这个变量可以从var RateLimiter = require('limiter').RateLimiter; var createCsvWriter = require('csv-writer').createArrayCsvWriter; var limiter = new RateLimiter(27, 'second', true); const csvWriter = createCsvWriter({ header: ['NAME'], path: './out.csv' }); /** Mocked module - you can delete this */ const nexmo = { numberInsight: { get: (item, cb) => { if (typeof cb !== 'function') { cb = () => {} } let msg = { status: 1, status_message: `${item.number} - have passed` }; cb(null, msg); } } } var final = ['john', 'mike', 'elise', 'valentine'] final = final.reduce((accumulator, item, index) => { return accumulator.then(() => { return new Promise(resolve => { limiter.removeTokens(1, (err, remainingReq) => { if (err) { resolve(Promise.resolve(err.message)); } else { nexmo.numberInsight.get({ level: 'basic', number: item }, (error, response) => { if (error) { resolve(Promise.resolve(error.message)); } else { csvWriter.writeRecords([ [response.status_message] ]).then(() => { resolve(response.status_message) }).catch(writerErr => { resolve(writerErr.message); }) } }) } }) }) }) }, Promise.resolve()); final.then(lastPromiseResponse => { console.log('final', lastPromiseResponse) }).catch(err => { console.log('final err', err); })提取时间

DateTime.now();

问题是,例如,如果时间是01:09:32,我得到的时间是1:9:32。

我如何获得常规格式的时间?

我可以使用if-else来做到这一点,但是我敢肯定有更好的方法

1 个答案:

答案 0 :(得分:6)

您可以尝试使用DateFormat,只需将pubspec.yaml包含intl依赖项

import 'package:intl/intl.dart';

DateTime now = DateTime.now();
String formattedTime = DateFormat.Hms().format(now);
print(formattedTime);

根据您的要求,您可以查看DateFormat

从DateFormat类获取的一些示例可以为您提供更多帮助。

String formattedTime = DateFormat.jm().format(now);           //5:08 PM
String formattedTime = DateFormat.Hm().format(now);           //17:08  force 24 hour time