My timestamp returns Timestamp(seconds=1560523991, nanoseconds=286000000) in a Flutter Firestore snapshot.
I want to print it as properly formatted date and time.
I'm using DateTime.now() to store current DateTime in Firestore while creating new records and retrieving it using Firestore snapshot but I am not able to convert to into formatted date time. I'm using lib intl.dart for formatting.
Code for saving data
d={'amount':amount,
'desc':desc,
'user_id':user_id,
'flie_ref':url.toString(),
'date':'${user_id}${DateTime.now().day}-${DateTime.now().month}-${DateTime.now().year}',
'timestamp':DateTime.now()
return Firestore.instance.collection('/data').add(d).then((v){return true;
}).catchError((onError)=>print(onError));
});
Accessing with
FutureBuilder(
future: Firestore.instance
.collection('data')
.where('user_id', isEqualTo:_user_id)
.getDocuments(),
builder: (BuildContext context,
AsyncSnapshot<QuerySnapshot> snapshot) {
if (!snapshot.hasData)
return Container(
child: Center(child: CircularProgressIndicator()));
return ListView.builder(
itemCount: snapshot.data.documents.length,
itemBuilder: (BuildContext context, int index) {
return Column(
children: <Widget>[
Text(DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toString())]);
....
Error thrown is
Invalid date format.
I'm expecting output is: 'Jan 17, 2019, 2:19 PM'
When we push the DateTime object to Firestore, it internally converts it to it's own timestamp object and stores it.
Method to convert it back to Datetime after fetching timestamp from Firestore:
Firestore's timestamp contains a method called toDate() which can be converted to String and then that String can be passed to DateTime's parse method to convert back to DateTime
DateTime.parse(timestamp.toDate().toString())
Here is way!
Firestore will return TimeStamp like Timestamp(seconds=1560523991, nanoseconds=286000000).
This can be parsed as
Timestamp t = document['timeFieldName'];
DateTime d = t.toDate();
print(d.toString()); //2019-12-28 18:48:48.364
You can directly convert the Firestore timestamp object to DateTime like this:
DateTime myDateTime = (snapshot.data.documents[index].data['timestamp']).toDate();
This will return your Firestore timestamp in the dart's DateTime format. In order to convert your DateTime object you can use DateFormat class from intl package.
You can use your obtained DateTime object to get the format of your choice like this:
DateFormat.yMMMd().add_jm().format(myDateTime);
This code produces an output like this:
Apr 21, 2020 5:33 PM
timestamp parameter is the time in seconds
String formatTimestamp(int timestamp) {
var format = new DateFormat('d MMM, hh:mm a');
var date = new DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
return format.format(date);
}
Please check this answer for intl date formats
Hope it helps !
I found Ashutosh's suggestion gives more user friendly output. A function like this is recommended in a helper class with a static method.
static convertTimeStamp(Timestamp timestamp) {
assert(timestamp != null);
String convertedDate;
convertedDate = DateFormat.yMMMd().add_jm().format(timestamp.toDate());
return convertedDate;
}
Intl package is require for DateFormat.
Once you've got a timestamp back from Firestore, something like
Timestamp(seconds=1560523991, nanoseconds=286000000)
you need to parse it into an object of type DateTime:
DateTime myDateTime = DateTime.parse(timestamp.toDate().toString());
print('$myDateTime');
This will give you something like:
2020-05-09 15:27:04.074
You can then format myDateTime like this:
String formattedDateTime =
DateFormat('yyyy-MM-dd – kk:mm').format(myDateTime);
print('$formattedDateTime');
That will give you:
2020-05-09 – 15:27
Use intl package:
Timestamp firebaseTimestamp = ...;
var date = firebaseTimestamp.toDate();
var output1 = DateFormat('MM/dd, hh:mm a').format(date); // 12/31, 10:00 PM
var output2 = DateFormat.yMMMd().format(date); // Dec 31, 2000
You will get a unix timestamp from firestore even if you send a DateTime to firestore.
You can parse a DateTime from Firestore with DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
The DateTime class has two option to return a sting. toIso8601String() or toString()
choose the one you need. Or use eg. DateTime.now().hour; to get the our and create your own output.
For more information: Check https://api.dartlang.org/stable/2.4.0/dart-core/DateTime-class.html
Using cloud firestore, Here's my what worked for me:
Text(snapshot.data["YouKey"].toDate().toString().substring(0,16))
subString is optionnal, I've added it because I had the clock time with many number after the minute (like 12:00 00:00:00)
It took a long time to find the perfect answer.
When you fetch the data from Firestore as a Timestamp object and you are sure about that then I will recommend you use the following code:
DateTime fetchedDate = e.data()["deadline"]?.toDate();
using ?.toDate() worked for me and hopefully will also work for you.
Timestamp t = document['time'] // Timestamp(seconds=1624653319,nanoseconds=326000000)
DateTime d = t.toDate();
print(d.toString()); //2021-06-25 18:48:48.364
Do like so:
DateFormat.yMMMd().add_jm().format(DateTime.parse(snapshot.data.documents[index].data['timestamp'].toDate().toString())]
First visit here for intl package,
then paste the package into your pubspec.yaml, run pub get (the usual way of updating pubspec).Import the package into your dart file and try out the below method.
String timestamp;
DateTime now = DateTime.now();
String formatDate =
DateFormat('yyyy-MM-dd – kk:mm').format(now);
timestamp = formatDate;
You should use fromMillisecondsSinceEpoch function.
var d = new DateTime.fromMillisecondsSinceEpoch(ts, isUtc: true);
Here ts is int type.
So we can convert Firebase timestamps to DateTime object as follows.
DateTime date = DateTime.fromMillisecondsSinceEpoch(timestamp.seconds * 1000);
Simple way to solve it.
//Declare a variable Timestamp and assign the value timestamp from database
Timestamp timestamp = document['timeFieldName'];
//Use DateTime's parse method to convert back to DateTime
DateTime _time =DateTime.parse(timestamp.toDate().toString())
//Use this method to get the H:m of the DateTime.
//You can choose the DateFormat you want.
String readTimeStamp(DateTime date)
{
var format =new DateFormat.Hm(); // My Format 08:00
return format.format(date);
}
There are different ways this can be achieved based on different scenario, see which of the following code fits your scenario.
Conversion of Firebase timestamp to DateTime:
document['timeStamp'].toDate()
(document["timeStamp"] as Timestamp).toDate()
DateTime.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch);
Timestamp.fromMillisecondsSinceEpoch(document['timeStamp'].millisecondsSinceEpoch).toDate();
If timeStamp is in microseconds use:
DateTime.fromMicrosecondsSinceEpoch(timestamp * 1000000);
If timeStamp is in milliseconds use:
DateTime.fromMillisecondsSinceEpoch(timestamp * 1000);
Add the following function in your dart file.
String formatTimestamp(Timestamp timestamp) {
var format = new DateFormat('yyyy-MM-dd'); // <- use skeleton here
return format.format(timestamp.toDate());
}
call it as formatTimestamp(document['timestamp'])
Note: To print this DateTime append toString()
I have to fetch hours and minutes from time format I am getting from the system however it is showing me error like int month= moment.Month;
DateTime productDate = DateTime.Now;
string twentyFourHourFormatHour =int.Parse(productDate.ToString("HH")).ToString();
Not picking up productdate when trying to store it in string (line 2)
DateTime has properties to expose all of the data you need. There is no need to do elaborate string manipulation.
DateTime date = DateTime.Now();
int hour = date.Hour;
int minute = date.Minute;
I’m trying to retrieve dates from the database then use it to compare with current date. How can I get the last date from a list of dates in the database then compare it with the current date? Here’s what I’ve tried but I get a exception: “LINQ to Entities does not recognize the method 'System.DateTime Last…”
var manageDate= from d in db.Enrollments.Select(da=>da.Date) select d;
var manageAssgnDate = from asgn in db.Enrollments.Select(asgn => asgn.Date) select asgn;
List<DateTime> newDate = manageDate.ToList();
I normally use lambdas:
// This gets the max date in the table
var manageDate = db.Enrollments.Max(da => da.Date);
Is this what you were asking for ?
Found a work-around:
var stdAssgn= from sa in db.Assignments where sa.StudentId==currentId select sa.Date;
var dt = stdAssgn.ToList().Last ();
String a = dt.ToString();
and to convert to DateTime if needed...
DateTime b=Convert.ToDateTime(a);
I have error:
Cannot implicitly convert type 'string' to 'System.DateTime'a
When I want get a DateTime
var dat = DateTime.Now.ToShortDateString();
godz.date = dat;
godz.data is type Date in database.
How fix it?
That's because you are trying to pass a string where a datetime is expected. Try changing to this:
var dat = DateTime.Now;
How about setting
godz.date = DateTime.Now;
am using C#, VS 2005 and SQL 2000
I have date conversion problem my SQL table having field as below
Fields:
datefrom
dateto
My SQL query in C# is
string sql = "insert into companymast (cname, datefrom, dateto) values(#cname, #datefrom, #dateto)";
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Parameters.Add("#cname",SqlDbType.Varchar(50)).Values = cname.text;
cmd.Parameters.Add("#datefrom",SqlDbType.Datetime).Values = maskedTextBox1.text;
cmd.Parameters.Add("#dateto",SqlDbType.Datetime).Values = maskedTextBox2.text;
cmd.ExecuteNonQuery();
But the above throw Error Like date non conversion string to date
I have to put date in dd/MM/yyyy format code, 103
so how do i do?
Help me out, please.
maskedBox1.text is a string. You're assigning that to a SqlParameter's data member, and it tries to convert whatever it receives to the data type you request.
A more solid solution would be to convert to DateTime explicitly, and pass the converted value to the SqlParameter. This way, you have more control over the conversion, and you'll see exactly where and why it goes wrong when it does. Example:
DateTime fromDate = DateTime.Parse(maskedTextBox1.text);
cmd.Parameters.Add("#datefrom",SqlDbType.Datetime).Values= fromDate;
For DateTime.Parse, see: http://msdn.microsoft.com/en-us/library/1k1skd40.aspx