0

i have struggled to subtract the date format values.

i/p:

if select day ('2016-02-14 20:10:10') - day ('2016-02-15 16:00:00') --- return 1

• then it will go to the loop.

I have to do some calculation inside that. but how to subtract the date value alone in the format and it should return 1 else come out from the condition

can anyone please help me

Thanks

1 Answers1

0

Here are three alternatives :

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class Test{

    public static void main(String[] arguments) {

        String sDateString = "2016-02-14 20:10:10";
        String eDateString = "2016-02-15 20:10:10";
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date startDate = null, endDate = null;
        try {
            startDate = df.parse(sDateString);
            endDate = df.parse(eDateString);
        } catch (Exception e) {
            e.printStackTrace();
        }

        //difference in milliseconds
        long diff = endDate.getTime() - startDate.getTime();

        //difference in days
        System.out.println(diff/(3600*24*1000));

        ///////////////////////////////////////////////////////////////
        //Alternatively , use java 8
        LocalDate startLocalDate = LocalDateFromDate(startDate);
        LocalDate endLocalDate = LocalDateFromDate(endDate);
        //difference in days
        System.out.println(ChronoUnit.DAYS.between(startLocalDate, endLocalDate));

        ///////////////////////////////////////////////////////////////
        //Alternatively, if the String representation of date is fixed
        //you can extract the string representing the day of the month
        //not recommended)

        //find index 0f last "-"
        int sIndex = sDateString.lastIndexOf("-");
        //get the day in month substring, remove spaces 
        String s = sDateString.substring(sIndex+1,sIndex+3).trim();

        int eIndex = sDateString.lastIndexOf("-");
        String e = eDateString.substring(sIndex+1,sIndex+3).trim();

        //difference in days
        System.out.println(Integer.parseInt(e) - Integer.parseInt(s));
    }

    public static LocalDate LocalDateFromDate(Date date) {

        Instant instant = Instant.ofEpochMilli(date.getTime());
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault())
                .toLocalDate();
    }
}
c0der
  • 18,467
  • 6
  • 33
  • 65
  • Hi, Thanks i am getting the result 1. –  Oct 15 '16 at 08:42
  • hi, can you please try my below task. http://stackoverflow.com/questions/40049875/how-to-write-a-udtf-code-for-the-below-task –  Oct 15 '16 at 08:45