我目前有一个滑块,范围从0到24,分为24个分区(即每个分区代表一个小时)。
我在下面编写了一个方法,该方法将滑块中的值转换为12小时时间格式,因此看起来像这样
String startingTimeDisplay() {
if (_lowerValue > 12) {
return (_lowerValue - 12.0).toStringAsFixed(0) + ':00 PM';
} else {
return (_lowerValue).toStringAsFixed(0) + ':00 AM';
}}
String endingTimeDisplay() {
if (_upperValue > 12) {
return (_upperValue - 12.0).toStringAsFixed(0) + ':00 PM';
} else {
return (_upperValue).toStringAsFixed(0) + ':00 AM';
}}
上述结果产生了
我可以使用DateTime.now()
访问当前日期和时间。
我正在尝试将滑块的时间范围从当前时间开始偏移到24小时,因此,例如,如果当前时间是下午3点,则滑块应从下午3点开始并在明天下午3点结束。有什么想法吗?
答案 0 :(得分:1)
您可以使用intl
的{{1}}而不是硬编码格式。这段代码:
DateFormat
产生:
import 'package:intl/intl.dart';
void main() {
DateTime now = DateTime.now();
print(now);
DateTime nowRounded = DateTime(now.year, now.month, now.day, now.hour);
DateTime tomorrowRounded =
DateTime(now.year, now.month, now.day + 1, now.hour);
print(nowRounded);
print(tomorrowRounded);
DateFormat usHour = DateFormat.jm();
print(usHour.format(nowRounded));
print(usHour.format(tomorrowRounded));
}
答案 1 :(得分:1)
class HomePage extends StatefulWidget {
@override
HomePageState createState() {
return new HomePageState();
}
}
class HomePageState extends State<HomePage> {
DateTime _plusDay;
DateTime _hourOnly;
var _lowerValue;
var _upperValue;
@override
void initState() {
var _time = DateTime.now();
_hourOnly = DateTime(_time.year, _time.month, _time.day, _time.hour);
_plusDay = _hourOnly.add(Duration(days: 1));
_lowerValue = _hourOnly.millisecondsSinceEpoch.toDouble();
_upperValue = _plusDay.millisecondsSinceEpoch.toDouble();
super.initState();
}
@override
Widget build(BuildContext context) {
DateFormat usHour = DateFormat.jm();
return Scaffold(
body: Center(
child: Container(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: <Widget>[
Text(
"${usHour.format(DateTime.fromMicrosecondsSinceEpoch(_lowerValue.toInt() * 1000))}"),
Expanded(
child: new RangeSlider(
min: _hourOnly.millisecondsSinceEpoch.toDouble(),
max: _plusDay.millisecondsSinceEpoch.toDouble(),
lowerValue: _lowerValue,
upperValue: _upperValue,
divisions: 24,
showValueIndicator: false,
valueIndicatorMaxDecimals: 1,
onChanged:
(double newLowerValue, double newUpperValue) {
setState(() {
_lowerValue = newLowerValue;
_upperValue = newUpperValue;
});
},
onChangeStart:
(double startLowerValue, double startUpperValue) {
print(
'Started with values: $startLowerValue and $startUpperValue');
},
onChangeEnd:
(double newLowerValue, double newUpperValue) {
print(
'Ended with values: $newLowerValue and $newUpperValue');
},
),
),
Text(
"${usHour.format(DateTime.fromMicrosecondsSinceEpoch(_upperValue.toInt() * 1000))}"),
],
),
//
],
),
),
),
),
);
}
}
使用https://stackoverflow.com/a/53992653/9478011将24小时转换为12小时