Firebase - retrieving data from a date - java

I want to retrieve data from a particular date from Firebase. They are stored in the following format:
I am using a datePicker to choose a date. But I am not able to figure out how I can change the date chosen to the above format.
For example: I choose a date say 28th March 2018. I would use the code:
int day = datePicker.getDayOfMonth();
String month = datePicker.getMonth() + "";
String year = datePicker.getYear() + "";
But I am not able to figure out how to change it to the following format, Wed Mar 28 2018 00:00:00 GMT+530 (IST)

After spending hours, trying to figure out a way, I have finally found a solution and have realized that this was a pretty silly question to ask. Nevertheless, this is what I have come up with,
int day = datePicker.getDayOfMonth();
int year = datePicker.getYear();
int month = datePicker.getMonth() + 1;
try {
SimpleDateFormat sdf = new SimpleDateFormat("d-M-yyyy");
Date date = sdf.parse(day + "-" + month + "-" + year);
sdf = new SimpleDateFormat("EEE MMM dd yyyy");
String strDate = sdf.format(date) + " 00:00:00 GMT+0530 (IST)";
Log.d("date_simple", strDate);
} catch (ParseException e) {
Log.d("date_simple", e + "");
e.printStackTrace();
}

Related

get year, month, day and time form "Tue, 12 Jan 2016 09:40:07 GMT" in Java/Android [duplicate]

This question already has answers here:
I want to get Year, Month, Day, etc from Java Date to compare with Gregorian Calendar date in Java. Is this possible?
(8 answers)
Closed 7 years ago.
I know these type of question asked lot's of time on lot's of website.
Till I not got solution that's why I am putting this question here.
I want year, month, date, date and time from date format
Tue, 12 Jan 2016 09:40:07 GMT
I am getting this date format form HttpResponse header and need year, month, date, date from this date format.
Following code I am using but not getting real value:
SimpleDateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
Date date;
try {
date = dateFormat.parse(header.getValue());// here we are getting date in format "Tue, 12 Jan 2016 09:40:07 GMT"
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("YEAR: " + calendar.YEAR);
System.out.println("MONTH: " + calendar.MONTH);
System.out.println("DATE: " + calendar.DATE);
} catch (ParseException e) {
e.printStackTrace();
}
I tried this also:
1.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
2.
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
But all the above code give following result:
YEAR: 1
MONTH: 2
DATE: 5
You are using calendar.YEAR, calendar.MONTH, and calendar.DATE the Calendar class contains static YEAR, MONTH and DATE variables so it print value of these variable i.e 1,2 and 5.
Instead of it use this:
System.out.println("YEAR: " + calendar.get(Calendar.YEAR));
System.out.println("MONTH: " + calendar.get(Calendar.MONTH));
System.out.println("DATE: " + calendar.get(Calendar.DATE));
Set timezone to Calendar instance to GMT.
SimpleDateFormat dateFormat = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss Z");
Date date;
try {
date = dateFormat.parse(header.getValue());// here we are getting date in format "Tue, 12 Jan 2016 09:40:07 GMT"
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); // set correct timezone to calendar
calendar.setTime(date);
System.out.println("YEAR: " + calendar.YEAR);
System.out.println("MONTH: " + calendar.MONTH);
System.out.println("DATE: " + calendar.DATE);
} catch (ParseException e) {
e.printStackTrace();
}

Convert String Date object to util.Date object with pattern MM/dd/yyyy [duplicate]

This question already has an answer here:
Converting the format of the date in java
(1 answer)
Closed 1 year ago.
getStartDate method returns util.Date type object. I need to a way to convert "today" which is String type Date object to util.Date object with the format of MM/dd/yyyy
If i format "today" String date to Date object I get long date format.
public Date getStartDate() {
try {
System.out.println("startDate" + startDate); // prints Fri Jan 02 00:00:00 EST 1998
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String today = formatter.format(startDate);
System.out.println("today" + today); // prints 02/01/1998 (I need to return Date object in this format)
DateFormat formatter2 = new SimpleDateFormat("MM/dd/yyyy");
Date reformatedDate = formatter2.parse(today);
System.out.println("reformatedDate" + reformatedDate); // Fri Jan 02 00:00:00 EST 1998
return reformatedDate;
} catch (Exception e) {
}
return null;
}
can do something like this to parse the date:
Format formatter = new SimpleDateFormat("MM/dd/yyyy");
String dateString = "02/01/1998";
Date date = null;
try {
date = (Date)((DateFormat) formatter).parse(dateString);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
String.format("%02d", month);
String.format("%02d", day);
String yourDate = month + "/" + day + "/" + year;

Convert month name to Date range

I need to convert Monthname + Year to a valid date range. It needs to work with leap years etc.
Examples
getDateRange("Feb",2015)
should find the range 2015-02-01 -- 2015-02-28
While
getDateRange("Feb",2016)
should find the range 2016-02-01 -- 2016-02-29
In Java 8, you can do that using TemporalAdjusters,
LocalDate firstDate= date.with(TemporalAdjusters.firstDayOfMonth());
LocalDate lastDate= date.with(TemporalAdjusters.lastDayOfMonth());
If you have only year and month, it is better to use YearMonth. From YearMonth you can easily get length of that month.
YearMonth ym= YearMonth.of(2015, Month.FEBRUARY);
int monthLen= ym.lengthOfMonth();
Java 8 made Date-Time operations very simple.
For Java 7 and below you could get away with something like this;
void getDate(String month, int year) throws ParseException {
Date start = null, end = null;
//init month and year
SimpleDateFormat sdf = new SimpleDateFormat("MMM");
Date parse = sdf.parse(month);
Calendar instance = Calendar.getInstance();
instance.setTime(parse);
instance.set(Calendar.YEAR, year);
//start is default first day of month
start = instance.getTime();
//calculate end
instance.add(Calendar.MONTH, 1);
instance.add(Calendar.DAY_OF_MONTH, -1);
end = instance.getTime();
System.out.println(start + " " + end);
}
The output would be for "Feb", 2015:
Sun Feb 01 00:00:00 EET 2015
Sat Feb 28 00:00:00 EET 2015
Java 7 solution with default Java tools:
public static void getDateRange(String shortMonth, int year) throws ParseException {
SimpleDateFormat format = new SimpleDateFormat("MMM yyyy", Locale.ENGLISH);
// the parsed date will be the first day of the given month and year
Date startDate = format.parse(shortMonth + " " + year);
Calendar calendar = Calendar.getInstance();
calendar.setTime(startDate);
// set calendar to the last day of this given month
calendar.set( Calendar.DATE, calendar.getActualMaximum(Calendar.DATE));
// and get a Date object
Date endDate = calendar.getTime();
// do whatever you need to do with your dates, return them in a Pair or print out
System.out.println(startDate);
System.out.println(endDate);
}
Try (untested):
public List<LocalDate> getDateRange(YearMonth yearMonth){
List<LocalDate> dateRange = new ArrayList<>();
IntStream.of(yearMonth.lengthOfMonth()).foreach(day -> dateRange.add(yearMonth.at(day));
return dateRange
}
Java 8 provides new date API as Masud mentioned.
However if you are not working under a Java 8 environment, then lamma date is a good option.
// assuming you know the year and month already. Because every month starts from 1, there should be any problem to create
Date fromDt = new Date(2014, 2, 1);
// build a list containing each date from 2014-02-01 to 2014-02-28
List<Date> dates = Dates.from(fromDt).to(fromDt.lastDayOfMonth()).build();

Calendar getTime() only returns EST

Calendar cl = Calendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
cl.setTimeInMillis(time);
Toast.makeText(getActivity(), cl.getTime().toString(), Toast.LENGTH_LONG).show();
What ever time I put it always returns the time in EST. I want it to return the time in PST. Does anyone know that could posibly be wrong?
P.S.
My local time is EST.
Try this:
TimeZone.setDefault(TimeZone.getTimeZone("PST"));
Calendar cl = Calendar.getInstance();
This isn't really an answer but it's too big to put into a comment. This is what I found.
My test looked like this
TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
Calendar cl = Calendar.getInstance(tz);
System.out.println(tz.getDisplayName());
String dayname = cl.getDisplayName(Calendar.DAY_OF_WEEK,Calendar.SHORT,Locale.US);
String monthname = cl.getDisplayName(Calendar.MONTH,Calendar.SHORT,Locale.US);
int hour = cl.get(Calendar.HOUR);
int min = cl.get(Calendar.MINUTE);
int sec = cl.get(Calendar.SECOND);
int mill = cl.get(Calendar.MILLISECOND);
int year = cl.get(Calendar.YEAR);
System.out.println("Time = " + cl.getTime().toString());
System.out.println("Manually = " +
dayname + " " + monthname + " " +
hour + ":" + min +":" + sec + ":" + mill + " " +
cl.getTimeZone().getDisplayName(Locale.US) + " " + year);
Which gave the output
Pacific Standard Time
Time = Tue Nov 05 11:36:33 EST 2013
Manually = Tue Nov 8:36:33:238 Pacific Standard Time 2013
Looking at Calendar.getTime():
public final Date getTime() {
return new Date(getTimeInMillis());
}
Following the bouncing ball...
public long getTimeInMillis() {
if (!isTimeSet) {
updateTime();
}
return time;
}
private void updateTime() {
computeTime();
// The areFieldsSet and areAllFieldsSet values are no longer
// controlled here (as of 1.5).
isTimeSet = true;
}
But I don't have the source for computTime() so that's where I stopped.
Gabriel's answer works, fwiw.
Calendar.getTime() returns a java Date instance which represents the number of milliseconds from the epoch January 1, 1970, 00:00:00 GMT. Calling toString() on a Date instance will print the date based on the timezone configured on the server. To properly format a date for output in another timezone, you'll want to look at using a date formatter.
TimeZone est = TimeZone.getTimeZone("America/New_York");
Calendar cal = Calendar.getInstance(est);
DateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
formatter.setTimeZone(est);
System.out.println(formatter.format(cal.getTime()));

Using SimpleDateFormat in java

I am trying the following code,
Calendar signupDate = Calendar.getInstance();
signupDate.set(Calendar.YEAR, 2014);
signupDate.set(Calendar.MONTH, 01);
signupDate.set(Calendar.DAY_OF_MONTH, 01);
Date signupDateTime = signupDate.getTime();
new Object[]{signupDateTime};
Date date = (Date) params[0];
String format = (String) params[1];
try {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.ENGLISH);
String expDateStr = (String) sdf.format(date);
System.out.println("Expiration Date: "+expDateStr);
} catch (Throwable t) {
throw new RuntimeException("Could not execute DateToString function for Date:" + params[0] + " with Pattern:" + params[1], t);
}
This program prints: Expiration Date: 2014-02-32
While debugging, i reached in into java.text.DateFormat class in Java API into the following function,
public final String format(Date date)
{
return format(date, new StringBuffer(),
DontCareFieldPosition.INSTANCE).toString();
}
Runtime value of date parameter for format function is: Fri Feb 01 17:58:30 PST 2013
But this function returns: 2014-02-32
I am not sure how does formatting converts 01 to 32.
Any suggestion?
Thanks,
Vijay Bhore
Feb 1st is the 32nd day of the year. Your SimpleDateFormat is probably using DD instead of dd.
This is dangerous:
signupDate.set(Calendar.MONTH, 01);
Don't use magic numbers like this since you or the next coder to maintain this code might not know that months are 0 based, that this sets the month to February not January.
Better:
signupDate.set(Calendar.MONTH, Calendar.JANUARY);
or
signupDate.set(Calendar.MONTH, Calendar.FEBRUARY);
Whichever was desired.

Categories

Resources