I have this code
if (obj.due_date != null) {
print('The date is '+obj.due_date);
print('now change to ' +
DateUtil().formattedDate(DateTime.parse(obj.due_date)));
}
DateUtil
import 'package:intl/intl.dart';
class DateUtil {
static const DATE_FORMAT = 'dd/MM/yyyy';
String formattedDate(DateTime dateTime) {
print('dateTime ($dateTime)');
return DateFormat(DATE_FORMAT).format(dateTime);
}
}
My output become this
I/flutter ( 5209): The date is 2019-11-20T00:00:00.000+08:00
I/flutter ( 5209): dateTime (2019-11-19 16:00:00.000Z)
I/flutter ( 5209): now change to 19/11/2019
Why it will change from 20 to 19?
It is because of the value that you hold in
obj.due_date
As per the log, the current value is
2019-11-20T00:00:00.000+08:00
When I used the below code
var tempDate = '2019-11-20T00:00:00.000+00:00';
print('The date is '+tempDate);
print('now change to ' +DateUtil().formattedDate(DateTime.parse(tempDate)));
the logs are as follows:
I/flutter (18268): The date is 2019-11-20T00:00:00.000+00:00
I/flutter (18268): dateTime (2019-11-20 00:00:00.000Z)
I/flutter (18268): now change to 20/11/2019
The only change between these codes is the value that we pass.
2019-11-20T00:00:00.000+00:00
It is purely a timezone issue.
Try below code
var tempDate = DateTime.now().toLocal().toString();
Log show
I/flutter (18268): 2019-11-15 16:06:54.786814
I/flutter (18268): The date is 2019-11-15 16:06:54.787186
I/flutter (18268): dateTime (2019-11-15 16:06:54.787186)
I/flutter (18268): now change to 15/11/2019
Likewise, when you use the following code
var tempDate = DateTime.now().toUtc().toString();
the logs are as follows:
I/flutter (18268): 2019-11-15 16:07:35.078897
I/flutter (18268): The date is 2019-11-15 05:07:35.079251Z
I/flutter (18268): dateTime (2019-11-15 05:07:35.079251Z)
I/flutter (18268): now change to 15/11/2019
Hence the final answer is, change below line
DateUtil().formattedDate(DateTime.parse(tempDate)));
to
DateUtil().formattedDate(DateTime.parse(tempDate).toLocal())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With