Weird part of DateTime.parse(data['datetime']) in Dart - flutter

Problem Description
I have 020-03-20T14:16:27.189282+08:00 return from my database and I am trying to convert it to 2:16pm using DateTime.parse(). However,every time I convert the time, I get 6:16am.
Question
May I know how could I solve this problem?
MyCode
dateTime = `020-03-20T14:16:27.189282+08:00`
time = DateFormat.jm().format(DateTime.parse(dateTime));
print(time);

Dai, thanks for your small tips.
Solutions for this question is remove the offset from the string.
Why
The result is always in either local time or UTC. If a time zone offset other than UTC is specified, the time is converted to the equivalent UTC time.
Read it here https://api.dart.dev/stable/2.7.1/dart-core/DateTime/parse.html.
Answered
String dateTime = `020-03-20T14:16:27.189282+08:00`;
int indexOfPlusMinusSymbol = dateTime .indexOf('+') >= 0
?dateTime .lastIndexOf('+')
: dateTime .lastIndexOf('-');
String time = DateFormat.jm().format(DateTime.parse(dateTime..substring(0, indexOfPlusMinusSymbol)));
print(time);

Related

What is the use case of millisecondssinceepoch in flutter

I would like to ask what is advantage of using the milliSecondsSincEepoch over normal DateTime in flutter?
Could anyone explain? Thank you in advnce for the answer!
return {
'createdAt': createdAt.milisecondsSinceEpoch,
'updatedAt': updatedAt.milisecondsSinceEpoch,
...
The millisecondsSinceEpoch property is the number of milliseconds since the "Unix Epoch" 1970-01-01T00:00:00Z (UTC).
This value is time zone independent.
This value is up to 8,640,000,000,000,000 milliseconds (100,000,000 days) since the Unix epoch. In other words: millisecondsSinceEpoch.abs() <= 8640000000000000.
Source: https://api.flutter.dev/flutter/dart-core/DateTime/millisecondsSinceEpoch.html

What's Swift current time Date object precision when it is initiated using the default constructor?

What's the current time Date object time precision when it is initiated using Date()? Does it capture the time to milliseconds?
let currentTime = Date()
print(currentTime) // 2022-10-09 09:13:39 +0000
When I print the date it only shows 2022-10-09 09:13:39 +0000 so I wonder if its precision is only to the second.
Does it capture the time to milliseconds?
Yes, it does. printing a date shows a fixed string description omitting the fractional seconds. A hint is that TimeInterval is defined as a floating point type (Double).
You can prove it
let interval = Date().timeIntervalSince1970
print(interval)
which shows a real fractional part rather than a Is-floating-point-math-broken value like .00000003

Parsing 24 HR Time to DateTime

I am attempting to convert the following 2HR time in String to a DateTime, so that I manage it appropriately.
"1800"
This question came close, but no one answered how to convert the String into a valid DateTime.
How to convert time stamp string from 24 hr format to 12 hr format in dart?
Attempt 1:
DateTime.parse("1800") -
Invalid Date Format
Attempt 2:
DateTime.ParseExact("1800") -
This doesn't seem to exist, although it shows up on various
Still no luck and need a second pair of eyes to point out the obvious to me.
The time by itself is not a datetime so you could do something like:
DateTime myTime(DateTime baseDate, String hhmm) {
assert(hhmm.length == 4, 'invalid time');
final _hours = int.parse(hhmm.substring(0, 2));
final _mins = int.parse(hhmm.substring(2, 2));
return DateTime(baseDate.year, baseDate.month, baseDate.day, _hours, _mins);
}
DateTime.parse expects to parse dates with times, not just times. (You can't even create a DateTime object without a date!)
Some people generate a dummy date string, but in your case you could trivially parse it with int.parse and then apply appropriate division and remainder operations:
var rawTime = int.parse('1800');
var hour = rawTime ~/ 100;
var minute = rawTime % 100;
Also see How do I convert a date/time string to a DateTime object in Dart? for more general DateTime parsing.

Convert Unix/epoch timestamp to human readable time in Dart Flutter

Say the EPOCH timestamp I received from an API is 1595216214.
It is equivalent to Monday, July 20, 2020 3:36:54 AM (GMT).
My interest is time value only (Ignoring the date/day value)? How can I code in Dart?
Also, how can I convert it into my time zone (E.g.: GMT+8)
you can use DateTime class to do that. Like this:
var dateUtc = DateTime.fromMillisecondsSinceEpoch(myAPIEpochTimeInMilliseconds, isUtc: true);
var dateInMyTimezone = dateUtc.add(Duration(hours: 8));
var secondsOfDay = dateInMyTimezone.hour * 3600 + dateInMyTimezone.minute * 60 + dateInMyTimezone.second;
NOTE:
If you are doing this for the web, although Dart does support 64+ bit numbers, javascript only takes 32-bit integers. So, use the BigInt class for big numbers tha exceeds 32-bit representation.
DateTime doesn't have an inherent timezone to be defined on the class. Is either the local (machine) time or utc Time. So, it is recomended to always use utc and add timezone offset when needed. Or just create a wrapper.

How to convert local date to UTC?

Can anyone help me with the following:
I have am recording date in my UI, which is IST +5:30
First, I want to convert that date to UTC with start time 00:00
Second, I want to convert that to long time (which I think it is
Unix)
Saved to DB
Third, I want to convert a long time back to UTC in format
MM/DD/YYYY.
This is what I tried so far:
const dateUnix => moment(myMomentObj)
.utc()
.format(DATE_TIME_FORMATS.TIME_STAMP);
The above gets a long time which I don't know if it correct.
const dateMoment = moment.unix(dateUnix)
const formatedDate = dateUnix.format('L'); //which should be in MM/DD/YYYY format
But the formatDate is giving me something like 02/12/15235 which is wrong.
Any help is appreciated.
Thanks in advance.
This code might help you
//input in IST +5:30
var inputDate = moment().utcOffset("+05:30").format();
console.log(inputDate);
//moment.unix outputs a Unix timestamp
var unixTs = moment.utc(inputDate).unix();
console.log(unixTs);
//there is a unix method that accepts unix timestamps in seconds followed by format to format it
var formattedDate = moment.unix(unixTs).format("MM/DD/YYYY");
console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>