How to print Firestore timestamp as formatted date and time - time

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()

Related

How to convert date time to UNIX in PowerBI for Desktop

I am new to powerBI I want to convert DateTime.LocalNow() to UNIX Timestamp
Use Duration.TotalSeconds
Duration.TotalSeconds(DateTime.LocalNow() - DateTime.FromText("1/1/1970"))
You can use this function:
let
fun_DateTimeToUnix = (optional DateTime as nullable datetime) as number =>
let
default_DateTime = if DateTime is null then DateTime.From(DateTimeZone.UtcNow()) else DateTime,
UnixDateTime = Duration.TotalSeconds(default_DateTime - DateTime.FromText("1/1/1970"))
in
UnixDateTime
in
fun_DateTimeToUnix
As shown:

D3 time string convert to date

I'm new to D3.
I have a string stored in a var, below is the var.
var expense = {"name":"jim","amount":34,"date":"11/12/2015"};
and I want to only show the year of the date.
var parser = d3.timeParse("%Y");
expense.date = parser(expense.date);
console.log(expense);
but I am just getting null for the date. Anyone know how to fix this? I should get the result:
{name: "jim", amount: 34, date: 2015 }
If you want to use d3 date tools, first you have the parse your string to date format
const tParser = d3.timeParse("%d/%m/%Y")
then use on your string
const date = tParser(expense.date)
then use d3.timeFormat("%Y")
const year = d3.timeFormat("%Y")(date)
Or much simpler just split your string as rioV8 commented
expense.date = +expense.date.split('/')[2]
Thought it could be useful to know how to use d3 time format works, more info

Fetch date and time in xamarin forms

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;

Date format in D3.js

I have a column (date) in csv which stores the date in "2003-02-01"(y-m-d). I would like to format the date in month and year like Apr 2003. how do i do that?
var format = d3.time.format("%m-%Y");
data.forEach(function(d,i) {
d.date = format(d.date);
});
I am getting the following error Error: TypeError: n.getFullYear is not a function Line: 5
the csv file contains values:
200,300,400,288,123,2003-01-01
300,700,600,388,500,2003-02-01
what is the issue here?
Javascript doesn't automatically recognize the values in the CSV file as dates, just reading them in as strings. d3's time functions make it pretty easy to convert them to datetime objects:
> parseDate = d3.time.format("%Y-%m-%d").parse
> parseDate('2003-01-01')
Wed Jan 01 2003 00:00:00 GMT-0600 (Central Standard Time)
To format the dates like you want, we need to go the other way, from a date object to a string:
> formatDate = d3.time.format("%b-%Y")
> formatDate(parseDate('2003-01-01'))
"Jan-2003"
I would recommend representing your dates within your program with date objects and only formatting them as strings when you need to display them.
D3 version 4 has different time methods now.
https://keithpblog.org/post/upgrading-d3-from-v3-to-v4/
https://github.com/d3/d3/blob/master/CHANGES.md
Your source date
var d = {created_time : "2018-01-15T12:37:30+0000"}
The structure of that date = %Y-%m-%dT%H:%M:%S%Z
I search google with "2018-01-15T12:37:30+0000" and it's suggestions provided the date structure string. Handy.
Create a timeParser to convert(parse) your date string into a date object
var parseDate = d3.utcParse("%Y-%m-%dT%H:%M:%S%Z")
//parseDate(d.created_time)
Now create a time formatter to return a formated date string for displaying.
var formatDate = d3.timeFormat("%b-%Y")
return formatDate(parseDate(d.created_time))
i.e.
Jan-1970
from Adam answer, here is a small helper function to convert a time string from a format to another:
var formatTime = function(input, formatInput, formatOutput){
var dateParse = d3.time.format(formatInput).parse;
var dateFormat = d3.time.format(formatOutput);
return dateFormat(dateParse(input));
};
use:
formatTime("2003-01-01", "%Y-%m-%d", "%b-%Y");
// output -> "Jan-2003"
if you are getting date lets say in variable " d = (e.g: '2003-03-01')" in string format then,
var monthNameFormat = d3.time.format("%b-%Y");
return monthNameFormat(new Date(d));
this will result date in "Jan-2003" format.
In D3Js v3, this worked for me:
var s = "2018-11-01T19:37:55Z";
d3.time.format("%Y-%m-%dT%H:%M:%SZ").parse(s);
// Thu Nov 01 2018 19:37:55 GMT-0700 (Pacific Daylight Time)

How to compare only dates in linq?

In linq how can i diffentiate the date, like in sql we use
datediff(mm,getdate(),getdate())=0
now how can i write in linq, can any body help me thank you.
I think this is what you want:
var query = from entity in entities
where entity.SomeDateTime.Date == anotherDateTime.Date
select entity;
This only compares dates and not times.
You can use this code for comparing two dates using linq in C#
DateTime d1 = myDate1;
DateTime d2 = myDate2;
TimeSpan t1 = d2.Subtract(d1);
totalDays = t1.Days;
There's nothing special in Linq about date and time handling, so we should look at the plain .Net facilities.
A DateTime in C# is a date and time.
To get just the date component in C#, try this:
var now = DateTime.UtcNow; // or DateTime.Now for local time/day
DateTime today = now.Date;
This will give you the date and time at midnight of the same day.
If you want to get the difference in days between two DateTime objects:
public TimeSpan DiffDates(DateTime d1, DateTime d2)
{
return d1.Date - d2.Date;
}
// ...
if(DiffDates(dateTime1, dateTime2) == TimeSpan.Zero)
{
// ...
}
Alternately you could check directly if the dates are equal:
if(dateTime1.Date == dateTime2.Date)
{
// ...
}
If you skip the .Date property, then you will get incorrect results.

Resources