0

I have One value of date time like "30-01-2014 22:50".

I have database of Date with same format but in datatype is String.

Now I want nearest time from database of given date-time "30-01-2014 22:50".

Example :

Value I have :"30-01-2014 22:50"

Database :

"30-01-2014 02:20"
"30-01-2014 05:30" 
"30-01-2014 22:55"
"30-01-2014 10:50"
"30-01-2014 22:54"`

So the output should be.

"30-01-2014 22:54"

How can I achieve this?

date1.after(date2) and date1.before(date3)

Is there any kind of function for time?

Thanks

Vamshi
  • 510
  • 2
  • 10
  • 26
Mayuri Ruparel
  • 694
  • 2
  • 11
  • 36

2 Answers2

1

Yes, there are. See the documentation here. The two methods you mentioned - after(Date when), and before(Date when) are part of the Date class.

Edit:

To accomplish what you're trying to do, you could sort your dates, then use Date.after(Date when) or Date.before(Date when) to find the pivot point of your data set. After that, you've narrowed it down to two remaining Dates, so all you have to do is compare these two dates with your comparison date to see which is closest.

For example:

if(`Math.abs(Date1.getTime() - DateCompare.getTime()) < Math.abs(Date2.getTime() - DateCompare.getTime()){
     return Date1;
} else {
     return Date2;
}
Submersed
  • 8,810
  • 2
  • 30
  • 38
  • Yes but how will I achieve my output? Any small hint – Mayuri Ruparel Jan 30 '14 at 15:08
  • You could make a List, sort it, then traverse your list to find the one closest to your specified date. It'd probably be easier to compare using Date.dateTime() since a valid date could be either before or after the date your comparing it too and still be valid. – Submersed Jan 30 '14 at 15:22
1

Get the milli seconds from each Date object and add it to Map then try to find the nearest one.

Otherwise, you can fetch the nearest date directly from DB using sql Query.

SELECT TOP 1 *
FROM x
WHERE x.date < @CurrentDate
ORDER BY x.date DESC

Source:Find closest date in SQL Server

Converting from Text to Date in SQl itselft.

Community
  • 1
  • 1
Noundla Sandeep
  • 3,334
  • 5
  • 29
  • 56