Diego Guerra
Diego Guerra

Reputation: 11

change the datetime format in flutter, to leave it only with the date

I would like to know how I can change the datetime format in flutter, to leave it only with the date. I also want to know if there is another widget that only contains the date.

Thanks

Upvotes: 1

Views: 12000

Answers (3)

Mahesh Jamdade
Mahesh Jamdade

Reputation: 20369

You can get the day month and year from DateTime object and convert it to string.

DateTime today = DateTime.now();
print(today); // prints 2019-12-15 00:00:00.000
DatetTime date = DateTime(today.year, today.month, today.day).toString().substring(0,10); 
print(date); // prints 2019-12-15

hope this helps

Upvotes: 2

Long Phan
Long Phan

Reputation: 897

You can use DateFormat from intl package. With it you can custom to any format that you need.

Add to pubspec.yaml

dependencies:
  intl: ^0.15.7

On Dart code:

import 'package:intl/intl.dart';

final dateFormatter = DateFormat('yyyy-MM-dd');
final dateString = dateFormatter.format(DateTime.now());

Then you can put the string into any widget. Example:

Text(dateString)

About date format: https://www.cl.cam.ac.uk/~mgk25/iso-time.html

Upvotes: 4

Sven
Sven

Reputation: 3414

Make a new DateTime and get the day from that:

var date = DateTime.now();
var result = "${date.year}/${date.month}/${date.day}";
print(result);  // prints 2019/3/6

Upvotes: 3

Related Questions