I have a date coming from a device and I want to do the following in Java:
I want to parse this date "2021-05-27T18:47:07+0530" to yyyy-mm-dd HH:MM:SS
Get the Date's offset value so that I can get the timezone offset as +05:30 or whatever timezone it comes from.
For the first one I have done this and looks like it works, but any better smaller approach will be handy as well:
String date = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
LocalDateTime inputDate = null;
String outputDate = null;
DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputPattern, Locale.ENGLISH);
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputPattern, Locale.ENGLISH);
inputDate = LocalDateTime.parse(date, inputFormatter);
outputDate = outputFormatter.format(inputDate);
System.out.println("inputDate: " + inputDate);
System.out.println("outputDate: " + outputDate);
The Ouput is:
inputDate: 2021-05-27T18:47:07.053
outputDate: 2021-05-27 18:47:07
I don't know how to get the offset value of timezone in this case.
There are many recommendations including using SimpleDateFormat and ZonedDateTime etc but should be the best answer for this considering the offset value can be dynamic i.e it can be +05:30,+09:00 etc.
Please help in this case.
Try it like this.
String dateTime = "2021-05-27T18:47:07+0530";
String inputPattern = "yyyy-MM-dd'T'HH:mm:ssZ";
String outputPattern = "yyyy-MM-dd HH:mm:ss";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ",
Locale.ENGLISH);
ZonedDateTime zdt = ZonedDateTime.parse(dateTime, dtf);
ZoneOffset tz = zdt.getOffset();
System.out.println(tz);
System.out.println(zdt.format(DateTimeFormatter.ofPattern(outputPattern,
Locale.ENGLISH)));
Prints
+05:30
2021-05-27 18:47:07
The zoned date time could also be reprinted using the same format by which it was originally parsed.
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()
Suppose I have a date in year-month-day format. Say "2015-02-12". Now I want to find that in which week this date lies. I mean 12 lies in 2nd week of Funerary. I want if I fo something like
LocalDate date = 2015-02-12;
date.getWeekOfMoth should gives me 2 because 2 lies in 2nd week of February. How can i do it ?
Thanks
Edit
Hi, I am so sorry. I should replied you before you asked. I tried with the following code
String input = "2015-01-31";
SimpleDateFormat df = new SimpleDateFormat("w");
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_MONTH);
System.out.println(week);
It prints 2.
While when I check with the following code
String valuee="2015-01-31";
Date currentDate =new SimpleDateFormat("yyyy-MM-dd").parse(valuee);
System.out.println(new SimpleDateFormat("w").format(currentDate));
It prints 5.
Try this one. Remember to feed it with your date format and string with this date as input.
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_MONTH);
I’m doing the code below in my view but I just get the month and number of the month in regards to 12 months of the year like this:
May 5 instead of May 14.
Here’s the code I have in my view:
#{
DateTime now = DateTime.Now;
String date = now.ToString("MMM");
}
What I want is the month and the date of the month. What am I doing wrong here?
Try
#{
DateTime now = DateTime.Now;
int month = now.Month;
string monthName=now.ToString("m").Split(' ')[1];
int day=now.Day;
}
String sql="select id from period where '"+systemDate+"' between startDate and endDate";
I need to execute this query and I am using oracle 10g. I want to get the id which falls between these dates. Problem I am facing is in oracle my date format is"dd-mon-yy" and systemDate is in format yyyy-mm-dd.So is ther any way to convert java date to dd-mon-format or any other way to execute the above query...
Kindly help.
You should convert your java.util.Date to a java.sql.Date and use a PreparedStatement as shown below:
java.util.Date jStartDate = ...; //your "java" date object
java.sql.Date startDate = new java.sql.Date(jStartDate.getTime());
java.util.Date jEndDate = ...;
java.sql.Date endDate = new java.sql.Date(jEndDate.getTime());
PreparedStatement p = connection.prepareStatement("select id from period where systemDate between ? and ?");
p.setDate(1, startDate);
p.setDate(2, endDate);
ResultSet rs = p.executeQuery();
Java has date formatting classes. DateFormat is the abstract parent class for these, SimpleDateFormat here is probably the one you want
SimpleDateFormat oracleStyle = new SimpleDateFormat("dd-MM-yy");
String dString = oracleStyle.format(systemDate);
String sql="select id from period where '"+systemDate+"' between startDate and endDate";
I havent tested this. The format call might need new string buffers as arguments, and my format string could be off, but this is the idea. Read the documentation