如何将Flutter的TimeOfDay转换为DateTime并转为毫秒时间戳存储?
Got it, let's walk through how to turn that TimeOfDay from your picker into a timestamp integer you can store in your database. The key here is that TimeOfDay only holds hours and minutes—so we need to pair it with a date to create a full DateTime object first.
Step 1: Combine TimeOfDay with a Date
Since TimeOfDay doesn’t include date information, you’ll want to attach it to a specific date. Most often, this is the current date (if you’re dealing with "today at X time"), but you could also use a user-selected date if you have a date picker paired with it.
Here’s how to do it with the current date:
// Your TimeOfDay from the picker TimeOfDay selectedTime = _timePickerResult; // Grab the current date DateTime currentDate = DateTime.now(); // Build a full DateTime using the current date + selected time DateTime combinedDateTime = DateTime( currentDate.year, currentDate.month, currentDate.day, selectedTime.hour, selectedTime.minute, );
If you’re working with a user-selected date (e.g., from a date picker), just replace currentDate with that selected date instead.
Step 2: Get the Millisecond Timestamp
Once you have your full DateTime, getting the integer timestamp is straightforward—use the millisecondsSinceEpoch property:
int timestamp = combinedDateTime.millisecondsSinceEpoch;
This integer is ready to be stored directly in your database.
Pro Tip: Use UTC for Consistent Storage
If your app will be used across time zones, it’s a good practice to store UTC timestamps to avoid confusion. To do this, convert your DateTime to UTC before grabbing the timestamp:
DateTime utcDateTime = combinedDateTime.toUtc(); int utcTimestamp = utcDateTime.millisecondsSinceEpoch;
Full Example Function
Wrap this logic into a reusable function to keep your code clean:
int convertTimeOfDayToTimestamp(TimeOfDay time, [DateTime? customDate]) { // Use custom date if provided, else use current date DateTime date = customDate ?? DateTime.now(); DateTime combinedDateTime = DateTime( date.year, date.month, date.day, time.hour, time.minute, ); // Uncomment below to use UTC instead // return combinedDateTime.toUtc().millisecondsSinceEpoch; return combinedDateTime.millisecondsSinceEpoch; }
Bonus: Convert Timestamp Back to TimeOfDay
When you retrieve the timestamp from the database, you can convert it back to a TimeOfDay like this:
int storedTimestamp = 1700000000000; // From your database DateTime retrievedDateTime = DateTime.fromMillisecondsSinceEpoch(storedTimestamp); TimeOfDay retrievedTime = TimeOfDay.fromDateTime(retrievedDateTime);
内容的提问来源于stack exchange,提问作者Robin Sinha

