-1

I am trying to get previous year from current year.

 private void lastyear() {
            pd = new ProgressDialog(getActivity());
            pd.setTitle("Please Wait...");
            pd.setCancelable(false);
            pd.show();

            Date lastyear = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(lastyear.getTime());
            calendar.add(Calendar.YEAR, -1);

            lastyear = new Date(calendar.get(Calendar.YEAR));
            Log.e("lastyear", String.valueOf(lastyear));


            db.collection("Orderers").document(user_id).collection("OpenOrders")
                    .whereEqualTo("OrderPlacedDateTime", lastyear)
                    .orderBy("OrderPlacedDateTime", Query.Direction.DESCENDING)
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {

                                ls_data.clear();

                                for (DocumentSnapshot document : task.getResult()) {

                                    if (document.exists()) {

                                        final String DeliveryMethod = (String) document.get("DeliveryMethods");
                                        final String ProductName = (String) document.get("ProductName");
                                        final Object Price1 = document.get("ProductPrice");
                                        final String Price = String.valueOf(Price1);
                                        final Object FinalPrice1 = document.get("FinalPrice");
                                        final String FinalPrice = String.valueOf(FinalPrice1);
                                        final String date = String.valueOf(document.get("OrderPlacedDateTime"));
                                        final String Orderid = (String) document.get("OrderId");
                                        final String image3 = (String) document.get("ProductImage");

                                        Model m = new Model();

                                        m.setName(ProductName);
                                        m.setPrice(Price);
                                        m.setDate(String.valueOf(date));
                                        m.setOrderid(Orderid);
                                        m.setimage3(image3);
                                        m.setFinalPrice(FinalPrice);
                                        m.setDeliveryMethods(DeliveryMethod);

                                        ls_data.add(m);

                                    }

                                }

                                try {
                                    adapter = new CustomAdapterOrders(getActivity(), ls_data, getActivity());
                                } catch (Exception ex) {
                                    Log.e("Error", "Dashboard : " + ex);
                                }

                                listView.setAdapter(adapter);
                                adapter.notifyDataSetChanged();
                                swipeLayout.setRefreshing(false);
                                listView.setVisibility(View.VISIBLE);
                                pd.dismiss();

                            }else{
                                pd.dismiss();
                                Toast.makeText(getActivity(), "No open orders yet", Toast.LENGTH_SHORT).show();
                                //listView.setAdapter(adapter);
                                listView.setVisibility(View.GONE);
                                //adapter.notifyDataSetChanged();
                                swipeLayout.setRefreshing(false);
                            }

                        }
                    });
        }

It should return me 2017 as result.But its returning wrong output as follows

a E/Filter  by:: Last year 05-21 10:43:44.676 11437-11437/com.bodaty.samyata.samyata E/lastyear: Thu Jan 01 00:00:02 GMT+00:00 1970

All the orders present in 2017 should be displayed Thanks inadvance

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
lasya valiveti
  • 251
  • 3
  • 12
  • It seems the problem is not only getting the year right, but also how to code a query that includes all date values in the given year. I don’t think `whereEqualTo` can do that.I don’t know what to do instead. I hope someone does. – Ole V.V. May 21 '18 at 19:54

4 Answers4

0

This is the initial problem:

lastyear = new Date(calendar.get(Calendar.YEAR));

That's creating a Date object with a "time in milliseconds since the Unix epoch" equal to the year of calendar. So you're creating a Date which is 2017 milliseconds after the Unix epoch: 1970-01-01T00:00:02.017Z, in other words. That explains your log message.

If you can possibly avoid the java.util.Date and java.util.Calendar classes, it's a good idea to do so (using java.time instead)... but if you have to use them, you want

lastyear = calendar.getTime();

That's the way to get a Date object corresponding to a Calendar object.

However, then you're still using it in the query like this:

.whereEqualTo("OrderPlacedDateTime", lastyear)

That would look for a document with that exact timestamp, which probably isn't what you want. If you want all orders in that year, you probably want to find the year (e.g. 2017), then create two Date values, one representing the start of 2017 and one representing the start of 2018, and use:

.whereGreaterThanOrEqualTo("OrderPlacedDateTime", startInclusive)
.whereLessThan("OrderPlacedDateTime", endExclusive)
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • It did not work sir. can you pls rewrite code in detail – lasya valiveti May 21 '18 at 11:07
  • @lasyavaliveti: No, because I don't know in what way it's wrong. You should only need to change that single line, assuming you want `lastyear` to be a `Date` value. What do you mean by "it did not work"? Please be *very* specific. – Jon Skeet May 21 '18 at 11:11
  • I suppose that `.whereEqualTo("OrderPlacedDateTime", lastyear)` gives you the orders that have exactly the date and time specified. Not all of the orders where the year is 2017. – Ole V.V. May 21 '18 at 19:49
  • @OleV.V.: Good point - although the OP then gave an answer themselves which still uses that. Will make a note in my answer. – Jon Skeet May 22 '18 at 06:04
0

Please change the following code:

Date lastyear = new Date();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(lastyear.getTime());
calendar.add(Calendar.YEAR, -1);

lastyear = new Date(calendar.get(Calendar.YEAR));
Log.e("lastyear", String.valueOf(lastyear));

to :

 Calendar now= Calendar.getInstance();// this has all the current time info including year
    now.add(Calendar.YEAR, -1); //now is 1 year less.

    Date lastyear= now.getTime();
    Log.e("lastyear", String.valueOf(lastyear));
ravi
  • 899
  • 8
  • 31
  • That now doesn't have a `lastyear` variable declaration at all, which means the code which tries to use it later will fail. It's not clear what you expect the argument to `whereEqualTo` to be now. – Jon Skeet May 21 '18 at 11:12
  • Yes, the main problem is there is this snippet, once the calendar year is deducted by 1 and that value is correctly retrieved. one can do `Date lastyear= new Date(now.get(Calendar.YEAR));` I will edit my answer – ravi May 21 '18 at 11:17
  • No, if you do `Date lastyear= new Date(now.get(Calendar.YEAR));` you'll still end up with a value in 1970 - see my answer. Fundamentally it's not clear why you expect your code to give a different result to the original code. – Jon Skeet May 21 '18 at 11:20
  • Oh I get what you are saying. I was wrong indeed. Thanks for pointing out. However I have found that using `Date lastyear = now.getTime();` does the trick. Done and tested. I will edit my answer again. Please undo the downvote. Since the code works after this edit. I have tested it. – ravi May 21 '18 at 11:35
  • I've removed the downvote, but you haven't explained either why the original code is broken or why your code would work. It's *only* the `now.getTime()` call that's relevant here, IMO. (The original code is pointless in terms of calling `setTimeInMilliseconds`, but that wouldn't actually be a problem.) – Jon Skeet May 21 '18 at 11:38
  • Yes. i intended the answer to be that way. IMHO one does not solve all issues at once, its more like solve one very small issue at a time. :) However the original question poster seems to have found the solution. – ravi May 21 '18 at 11:41
  • So if you only want to fix one problem at a time, why have you included more change than is necessary? As my answer explains, *all* that's needed is to change to use `now.getTime()`. The rest of the changes you've made are improvements but they're unrelated to the problem IMO, and you haven't explained them. – Jon Skeet May 21 '18 at 11:43
  • Okay. I will try to explain more next time. However I do not know what changes you are talking about. I merely changed like 3 lines. And for us non-native speakers sometimes code change speak more than all the verbose English. – ravi May 21 '18 at 11:47
  • I'm not saying you shouldn't include the code change - but it's worth explaining it as well. My point is that you've made completely irrelevant changes - when the *only* relevant part is calling `now.getTime()`. Why include that change at all? – Jon Skeet May 21 '18 at 11:50
  • Oh. Now I get what you are talking about. For a second, I thought you were just babbling. But your point is right. You mean I just edited one line and deleted 2 lines , so why include all the code as a change? Its just because I like it that way. No particular reason. – ravi May 21 '18 at 11:54
0

Here is the answer. Just need to change one single line

 private void lastyear() {
        pd = new ProgressDialog(getActivity());
        pd.setTitle("Please Wait...");
        pd.setCancelable(false);
        pd.show();

//        Date lastyear = new Date();
//        Calendar calendar = Calendar.getInstance();
//        calendar.setTimeInMillis(lastyear.getTime());
//        calendar.add(Calendar.YEAR, -1);
//
//        lastyear = new Date(calendar.get(Calendar.YEAR));

        Date lastyear = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(lastyear.getTime());
        calendar.add(Calendar.YEAR ,-1);
        lastyear = new Date(calendar.getTime().getTime());
        Log.e("lastyear", String.valueOf(lastyear));


        db.collection("Orderers").document(user_id).collection("OpenOrders")
                .whereEqualTo("OrderPlacedDateTime", lastyear)
                .orderBy("OrderPlacedDateTime", Query.Direction.DESCENDING)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {

                            ls_data.clear();

                            for (DocumentSnapshot document : task.getResult()) {

                                if (document.exists()) {

                                    final String DeliveryMethod = (String) document.get("DeliveryMethods");
                                    final String ProductName = (String) document.get("ProductName");
                                    final Object Price1 = document.get("ProductPrice");
                                    final String Price = String.valueOf(Price1);
                                    final Object FinalPrice1 = document.get("FinalPrice");
                                    final String FinalPrice = String.valueOf(FinalPrice1);
                                    final String date = String.valueOf(document.get("OrderPlacedDateTime"));
                                    final String Orderid = (String) document.get("OrderId");
                                    final String image3 = (String) document.get("ProductImage");

                                    Model m = new Model();

                                    m.setName(ProductName);
                                    m.setPrice(Price);
                                    m.setDate(String.valueOf(date));
                                    m.setOrderid(Orderid);
                                    m.setimage3(image3);
                                    m.setFinalPrice(FinalPrice);
                                    m.setDeliveryMethods(DeliveryMethod);

                                    ls_data.add(m);

                                }

                            }

                            try {
                                adapter = new CustomAdapterOrders(getActivity(), ls_data, getActivity());
                            } catch (Exception ex) {
                                Log.e("Error", "Dashboard : " + ex);
                            }

                            listView.setAdapter(adapter);
                            adapter.notifyDataSetChanged();
                            swipeLayout.setRefreshing(false);
                            listView.setVisibility(View.VISIBLE);
                            pd.dismiss();

                        }else{
                            pd.dismiss();
                            Toast.makeText(getActivity(), "No open orders yet", Toast.LENGTH_SHORT).show();
                            //listView.setAdapter(adapter);
                            listView.setVisibility(View.GONE);
                            //adapter.notifyDataSetChanged();
                            swipeLayout.setRefreshing(false);
                        }

                    }
                });
lasya valiveti
  • 251
  • 3
  • 12
  • 1
    You haven't shown what line you've changed, or explained *why* you changed it, which makes this fairly unhelpful as an answer IMO. Additionally, using `new Date(calendar.getTime().getTime())` is significantly more long-winded than just calling `calendar.getTime()`, but should achieve the same result... and you claimed in comments on my answer that that didn't work anyway. – Jon Skeet May 21 '18 at 11:40
0
   Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.YEAR,-1);
    String year = new SimpleDateFormat("yyyy", Locale.US).format(calendar.getTime());
    Toast.makeText(this, ""+ year, Toast.LENGTH_SHORT).show();

Try this

Jay Thummar
  • 2,281
  • 1
  • 14
  • 22
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. May 21 '18 at 19:45