Firestore Timestamp to ArrayList<String> and then to Date - java

I have a static ArrayList being populated at startup from Firebase to store a variety of values. One of the FB fields I need to store is a Timestamp.
I need to store the Timestamp in my array, but then display it later in a readable Date format.
Initialise the ArrayList:
static ArrayList<String> suspectedValues = new ArrayList();
Get the timestamp from FB:
Timestamp dtg = (Timestamp) document.getData().get("dtg");
Set the timestamp as a String and store in the Array:
String timeStamp = String.valueOf(dtg);
String suspectedData [] = {timeStamp};
suspectedValues.addAll(Arrays.asList(suspectedData));
Later in a different activity onCreate:
int counter = 0;
for(int i = 0; i < suspectedValues.size(); i = i + 4){
String timeStamp = suspectedValues.get(4);
Date dtg = new Date(Long.parseLong(timeStamp));
gMap.addMarker(new MarkerOptions().position(latLng).title(suspected).snippet("id: " + id + " | " + taggedAt + ": " + dtg).icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
if(suspectedValues.size() != 0){
counter = counter + 4;
}
}
I have tried a number of different conversions between Timestamp, Date and String but cant get this to work. When I try to set the Date dtg I get:
java.lang.NumberFormatException: For input string: "56.504800874303676"
at java.lang.Long.parseLong(Long.java:594)
at java.lang.Long.parseLong(Long.java:636)
I have also tried:
Timestamp dtg = (Timestamp) document.getData().get("dtg");
Date date = dtg.toDate();
String timeStamp = date.toString();
String suspectedData [] = {timeStamp};
suspectedValues.addAll(Arrays.asList(suspectedData));
with:
String timeStamp = suspectedValues.get(4);
Date theSameDate = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").parse(timeStamp);
But it keeps throwing a Parse exception.
Timestamp from FB: Timestamp(seconds=1583706187, nanoseconds=895000000)
Converted to Date: Sun Mar 08 22:23:07 GMT 2020
timestamp String going into Array: Sun Mar 08 22:23:07 GMT 2020
timestamp String coming out of Array: 62.76105524614817
I/MapsActivity: ParseException: java.text.ParseException: Unparseable date: "62.76105524614817"

Ok, I figured a workaround,
I created two separate ArrayLists, one accepts String and the 2nd accepts Date.
static ArrayList<String> suspectedValues = new ArrayList();
static ArrayList<Date> suspectedDateValues = new ArrayList<>();
I put all my Dates in the 2nd ArrayList instead of the 1st.
I also created 2 counters.
int counter = 0;
int counter1 = 0;
I know that I have a date after every 3 values in the first ArrayList. So as I iterate through the 1st list, I call a new method, passing in all the values from the 1st method, which retrieves the date from the 2nd ArrayList and uses the date alongside the passed values to execute my tasks.
for(int i = 0; i < suspectedValues.size(); i = i + 3){
[snip]
getSuspectedDate(lat, lng, gMap, counter1, passedActivity, id, smallMarker);
if(suspectedValues.size() != 0){
counter = counter + 3;
counter1 = counter1 + 1;
}
}
And my final method executed on each iteration of the for loop above:
public void getSuspectedDate(double lat, double lng, GoogleMap gMap, int counter1, Activity passedActivity, String id, Bitmap smallMarker){
String suspected = passedActivity.getResources().getString(R.string.suspected);
String taggedAt = passedActivity.getResources().getString(R.string.taggedDTG);
Date date = suspectedDateValues.get(counter1);
String dtg = String.valueOf(date);
LatLng latLng = new LatLng(lat, lng);
gMap.addMarker(new MarkerOptions().position(latLng).title(suspected).snippet("id: " + id + " | " + taggedAt + ": " + dtg).icon(BitmapDescriptorFactory.fromBitmap(smallMarker)));
}
Not the cleanest solution, but it works!

Related

How to get users click in calendar view to be stored as dd/mm/yyyy in SQLite

In my SQLite database I have my dates stored in this format 02/01/2023 but when I try to get the date from the calendarview it gives them to me as 2/1/2023 which causes me to have an error when trying to retrieve the data from the database that matches that date.
How do I format this into a String variable?
My attempt so far:
public void onSelectedDayChange(#NonNull CalendarView calendarview, int i, int i1,int i2) {
exercise_name = new ArrayList<>();
set_weight = new ArrayList<>();
set_reps = new ArrayList<>();
set_date= new ArrayList<>();
//formatting to dd/mm/yyyy
System.out.println("both are over 10");
date = i2 + "/" + (i1+1) + "/" + i;
//month needs plus 1 because it starts at 0
tviewdate.setText(date);
storeDataDateinArrays();
There is a better way (than what you have posted as an answer) to get the required formatted string:
String output = String.format("%02d/%02d/%d", day, month, year);
where day, month and year are integers.
Using java.time API:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
class Main {
public static void main(String[] args) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");
// Sample units
int year = 2023, month = 2, day = 1;
LocalDate date = LocalDate.of(year, month, day);
String output = date.format(formatter);
System.out.println(output);
}
}
Output:
01/02/2023
ONLINE DEMO
Learn more about the modern Date-Time API from Trail: Date Time.
This is how i got it to work:
String sYear = String.valueOf(Year);
String sMonth = String.valueOf((Month + 1));
String sDay = String.valueOf(Day);
if (sDay.length() == 1)
sDay = "0" + sDay;
if (sMonth.length() == 1)
sMonth = "0" + sMonth;
if (sDay.length() == 1)
sDay = "0" + sDay;
date = sDay + "/" + sMonth + "/" + sYear;

Android - take a custom string

I have a file path name whose prefix always changes as below :
"Unregistered_2018-05-02_14.40.04_+621241411112_34243555523.mp3"
"Martin_2018-04-01_03.10.40_+111_5213441935.mp3"
"Byan_2018-01-04_04.70.01_+62994_2313325553.mp3"
How can I retrieve date (2018-01-04), time (04.70.01) and number phone (+111) with the ever-changing data ?
Whoever you are I am very grateful to finish this
You can use split with _ like this :
String[] texts = new String[] {
"Unregistered_2018-05-02_14.40.04_+621241411112_34243555523.mp3",
"Martin_2018-04-01_03.10.40_+111_5213441935.mp3",
"Byan_2018-01-04_04.70.01_+62994_2313325553.mp3",
};
for (String text : texts) {
String[] split = text.split("_");
String date = split[1];
String time = split[2];
String phone = split[3];
System.out.println("date = " + date + ", time = " + time + ", phone = " + phone);
}
Outputs
date = 2018-05-02, time = 14.40.04, phone = +621241411112
date = 2018-04-01, time = 03.10.40, phone = +111
date = 2018-01-04, time = 04.70.01, phone = +62994

java parse date time with milliseconds into date getting parse error

I have a string in which I am finding the datetime with milliseconds as follows:
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if(monthup.length()==1){monthup="0"+monthup;}
if(dayup.length()==1){dayup="0"+dayup;}
if(hourup.length()==1){hourup="0"+hourup;}
if(minuteup.length()==1){minuteup="0"+minuteup;}
if(secondup.length()==1){secondup="0"+secondup;}
if(millisup.length()==1){millisup="0"+millisup;}
if(millisup.length()==2){secondup="00"+millisup;}
String timewithmilsec = year+ monthup + dayup+ hourup+ minuteup+ secondup+ millisup;
System.out.println(timewithmilsec);
I am getting a value: 20151020115216690 which is obviousely correct.
I want to parse it to java Date format.
What I did is as follows:
try{
DateFormat formatter = new SimpleDateFormat("yyyyMMdHHmmssaaa");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
}
catch(Exception e){
System.out.println(e);
}
I am getting an error as follows:
java.text.ParseException: Unparseable date: "20151020115247995"
You have only one d in your format, but are padding the day to two characters, also, according to the JavaDocs...
a Am/pm marker Text PM
which isn't a millisecond place holder, I think you mean SSS
For example...
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
int month = now.get(Calendar.MONTH) + 1; // Note: zero based!
int day = now.get(Calendar.DAY_OF_MONTH);
int hour = now.get(Calendar.HOUR_OF_DAY);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
int millis = now.get(Calendar.MILLISECOND);
String monthup = String.valueOf(month);
String dayup = String.valueOf(day);
String hourup = String.valueOf(hour);
String minuteup = String.valueOf(minute);
String secondup = String.valueOf(second);
String millisup = String.valueOf(millis);
if (monthup.length() == 1) {
monthup = "0" + monthup;
}
if (dayup.length() == 1) {
dayup = "0" + dayup;
}
if (hourup.length() == 1) {
hourup = "0" + hourup;
}
if (minuteup.length() == 1) {
minuteup = "0" + minuteup;
}
if (secondup.length() == 1) {
secondup = "0" + secondup;
}
if (millisup.length() == 1) {
millisup = "0" + millisup;
}
if (millisup.length() == 2) {
secondup = "00" + millisup;
}
String timewithmilsec = year + monthup + dayup + hourup + minuteup + secondup + millisup;
System.out.println(timewithmilsec);
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
Date date = formatter.parse(timewithmilsec);
System.out.println(date);
} catch (Exception e) {
System.out.println(e);
}
Which for me prints
20151020173034124
Tue Oct 20 17:30:34 EST 2015
And while I'm at it, let me introduce you to String.format, which can reduce all you int to String conversion and padding code down to...
String timewithmilsec = String.format("%04d%02d%02d%02d%02d%02d%03d", year, month, day, hour, minute, second, millis);
I am getting Tue Oct 20 12:04:08 IST 2015 but interestingly I did not see any millisecond here
Date#toString won't include the milliseconds by default, you will need to supply a DateFormat which can.
If I replace the last System.out.println with System.out.println(new SimpleDateFormat("dd MMM yyyy HH:mm:ss.SSS").format(date)); it prints something like
20 Oct 2015 17:37:14.856
(for the value 20151020173714856)
According to documentation letter S responds to milliseconds so your format should look like this new SimpleDateFormat("yyyyMMddHHmmssSSS"); (you have one d in your format).
The answer is the missing "d" in the date format, where #MadProgrammer depicts.
In addition, the generation of the string representation of the date should be reconsidered. You should use SimpleDateFormat.format() to generate date string as in the sample code below:
Calendar now = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String formattedDate = formatter.format(now.getTime());
System.out.println("Formatted date: " + formattedDate);
And the output will be in a format that you requested.
Formatted date: 20151020094934279

Java get int numbers from DateFormat and have user Input

In my code I want to have the individual numbers from date format so I can use them as int values:
public static final String DATE_FORMAT = "dd.MM.yyyy";
public int age()
{
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
// How to convert to int?
int currentnDay = ?;
int currentMonth = ?;
int currentYear = ?;
}
also I would like some user input to define day,month and year in one go, if that's even possible:
private Date dateOfPublication;
public void input()
{
Scanner scn = new Scanner( System.in );
System.out.print( "Please enter dateOfPublication: " );
// How to setup input for this?
}
I hope you can help me out, previously I did it all seperatly but the code was quite big and I think it would be prettier if I could do it like that..
update: okay I'm doing the input like this now:
System.out.print( "Please enter dateOfPublication, use format of x.x.xxxx: " );
userInputDate = scn.next();
String[] ary = userInputDate.split("\\.");
publicationDay = Integer.parseInt(ary[0]);
publicationMonth = Integer.parseInt(ary[1]);
publicationYear = Integer.parseInt(ary[2]);
thanks for your help!
Take a look at Java 8's new Time API (or JodaTime or Calendar if you're really stuck)
LocalDate ld = LocalDate.parse("16.10.2015", DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue());
System.out.println(ld.getYear());
Which outputs
2015-10-16
16
10
2015
Now, you could simply ask the user to input a date in a given format and try and parse the result, if the parsing fails, you could reprompt them
For example...
Scanner input = new Scanner(System.in);
LocalDate ld = null;
do {
System.out.print("Please enter date in " + DATE_FORMAT + " format: ");
String value = input.nextLine();
try {
ld = LocalDate.parse(value, DateTimeFormatter.ofPattern(DATE_FORMAT));
} catch (Exception e) {
System.err.println(value + " is not a valid date for the format of " + DATE_FORMAT);
}
} while (ld == null);
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue()); // Is probably 0 indexed
System.out.println(ld.getYear());
You can use:
dateFormat.format(today).split("\\.");
For your code:
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
String[] dateArr = dateFormat.format(today).split("\\.");
int currentnDay = Integer.parseInt(dateArr[0]);
int currentMonth = Integer.parseInt(dateArr[1]);
int currentYear = Integer.parseInt(dateArr[2]);
IdeOne Example
First, you have to parse the input string
The Calendar data type is more flexible for date-time handling. This is an example that shows some Date/Calendar operations.
Date date;
Calendar c;
// Get the current date
c = Calendar.getInstance();
System.out.println("Current Calendar:" + c.getTime().toString());
int currentnDay = c.get(Calendar.DATE);
int currentMonth = c.get(Calendar.MONTH);
int currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Current Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
String DATE_FORMAT = "dd.MM.yyyy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
date = dateFormat.parse("11.10.1981");
System.out.println("Modified Date:" + date.toString());
// reset Calendar
c = Calendar.getInstance();
// set date to the calendar
c.setTimeInMillis(date.getTime());
currentnDay = c.get(Calendar.DATE);
currentMonth = c.get(Calendar.MONTH);
currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Modified Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
This is the output of the example.
Current Calendar:Thu Oct 15 20:22:59 EDT 2015
Current Values: 15/9/2015
Modified Date:Sun Oct 11 00:00:00 EDT 1981
Modified Values: 11/9/1981

Java Regex find() vs match() usage

Edited question
I want to pull the date and time out of some strings. Here's an example. All Event strings start with [0r(1)2[000p[040qe1w3h162[020t*. upon encountering a new one, it should parse the last string set and get some data. an example event is below
[0r(1)2[000p[040qe1w3h162[020t*881*11/11/2010*12:24*
*EVENT STARTED*
[020t 12:24:06 SMARTCARD ENTERED
11\11\10 12:24 10390011
123456789098765432 6598
INVALID TRANSACTION, PLEASE CONTACT
ADMIN FOR ADVICE
-----------------------------------
[020t 12:24:52 FILE STACKED
[020t 12:24:59 FILE PRESENTED 0,5,0,0
[020t 12:25:03 FILE TAKEN
11\11\10 12:25 10390011
123456789098765432 6599
WITHDRAW FILES10.00
[000p[040q(1 *6599*1*E*000050000,M-00,R-10200
-----------------------------------
[020t 12:25:34 SMARTCARD TAKEN
[020t 12:25:38 EVENT ENDED
I want to extract date and time as one variable for every activity. e.g.
Activity= EVENT STARTED
Activity time/date= 11/11/2010 12:24
Activity= SmartCard inserted
Activity time/date= 12:24:06
I tried the following
/*
String sample = "[0r(1)2[000p[040qe1w3h162[020t*882*11/11/2010*12:26*";
String regex = "(?x) ^([0r(1)2[000p[040qe1w3h162[020t*):// ([^/:]+) (?:(\\d+))?";
Matcher m = Pattern.compile(regex).matcher(sample);
if(m.find())
{
String ignore = m.group();
String date = m.group(1);
String time = m.group(2);
System.out.println( date + " " + time);
}
*/
//this section isn't useful in light of the edit to the question
Use String.split(String regex):
String line = "[0r(1)2[000p[040qe1w3h162[020t*882*11/11/2010*12:26*";
String[] parts = line.split("\\*");
String date = parts[2];
String time = parts[3];
System.out.println("date=" + date + ", time=" + time);
Output:
date=11/11/2010, time=12:26
class sql
{
public static void main (String [] args)
{
String dateInCase = "11/11/2010";
String termID;
String line = " 11\11\10 12:24 10390011";
String[] parts = line.split("");
String termId = parts[4]+parts[5]+parts[6]; //to catch terminal ID
String cardInserted = parts[1]+parts[2]+parts[3]+parts[4]+parts[5];
String starter = parts[4]+parts[7]+parts[13]+parts[14]+parts[15];
String tracker = parts[3]+parts[4]+parts[5]+parts[6]+parts[7];
boolean V = (termId.matches("\\s\\d\\d"));
boolean W = (cardInserted.matches("\\s\\s\\s\\s\\s"));//this gets card inserted
boolean X = (starter.matches("\\D\\d\\d\\d\\d"));// a new event set has started
boolean Y = (tracker.matches("\\d\\d\\d\\D\\s")); // this checks for any activity as all activities have numbers in 3,4,5
System.out.println(V);
System.out.println(W);
System.out.println(X);
System.out.println(Y);
if(V == true)
{
parts = line.split("\\ ");
String terminal = parts[2];
System.out.println("terminal " + terminal);
}
if(W == true)//this gets card inserted strings
{
parts =line.split("\\*");
String activity = parts[1];
System.out.print(activity);
}
if(X == true) //action if it sees a new event set
{
parts = line.split("\\*");
String datetime = parts[2]+" "+ parts[3];
System.out.println("time= " + datetime);
dateInCase = parts[2];
}
if(Y == true) //action if it sees a new event
{
parts =line.split("\\ ");
String datetime = dateInCase+ " " + parts[1];
String activity = parts[2]+ " " + parts[3];
System.out.println("time= " + datetime + " activity= " + activity);
}
}
}

Categories