find out the date from an input string - java

I am trying to find out the specific date from a given input string, which can be like "201411W3". I know that the week is 3rd from this string(W3) and the event will be on Friday, so I want to find the date of the 3rd Friday. I did something like this:
public static Date getLastFriday( int month, int year ) {
Calendar cal = Calendar.getInstance();
cal.set( year, month, 1 );
cal.add( Calendar.DAY_OF_MONTH, - ( cal.get( Calendar.DAY_OF_WEEK ) % 7 + 8 ) );
return cal.getTime();
}
when I call this method: getLastFriday(11, 2014), I get the value "Fri Nov 21 13:16:57 EST 2014" which I need to parse to find out the date. is there any way to get just the date from the result?
Thanks!

If I understood you, then you can use below code as reference -
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class Test{
public static void main (String[] args)
{
String str="201411W3";
String[] strSplitted = str.split("W");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MONTH, Integer.parseInt(strSplitted[0].substring(4,6))-1);
calendar.set(Calendar.YEAR, Integer.parseInt(strSplitted[0].substring(0,4)));
calendar.set(Calendar.DAY_OF_MONTH, 1);
if(calendar.get(Calendar.DAY_OF_WEEK)==7)
{
calendar.set(Calendar.WEEK_OF_MONTH, Integer.parseInt(strSplitted[1])+1);
}
else
{
calendar.set(Calendar.WEEK_OF_MONTH, Integer.parseInt(strSplitted[1]));
}
calendar.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
String formattedDate = new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime());
System.out.println(formattedDate);
}
}
Output : 2014-11-21 You can change the format to any format you want.

If you just want to get the month and day without the seconds, you could call .get(Calendar.MONTH) and .get(Calendar.DATE) and pass them into the constructor of a new date object and return that object.
More info: here

Use this SimpleDateFormat
I didn't test the following code but it will work like:
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date myDate = sdf.parse("Fri Nov 21 13:16:57 EST 2014");

Related

java.util.date get milliseconds for y-m-d only

Situation: There is an Object AuditLog, which contains the variable java.util.Date date. This Object is saved in a mySQL Database.
#Entity
public class AuditLog implements Persistable<Long> {
...
#Temporal(TemporalType.DATE)
private Date date;
...
}
I am writing some JUnit tests and need to verify that a saved Date equals the actual date. Where date is a local Copy of the value actually passed to the log Object before it got saved and then loaded again.
Assert.assertEquals(date, log.getDate());
Output:
expected:<Wed May 24 15:54:40 CEST 2017> but was:<2017-05-24>
So you can see that the date actually is the right one but only y-m-d
I then tried this (below) to check if the milliseconds get altered.
Assert.assertEquals(date.getTime(), log.getDate().getTime());
Output:
expected:<1495634973799> but was:<1495576800000>
Now i think the best way would be to get the Milliseconds for year month day only.
Question: Can this be achieved relatively simple and should i do this? I think the Date gets altered because of a Database operation of some kind, so adapting the Test is OK right?
There are two ways to do this:
Using local date : You can convert util Date to LocalDate and do assertEquals on both the objects. LocalDate won't have time, e.g.:
Date input = new Date();
LocalDate date = input.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
System.out.println(date);
Using Apache commons' DateUtils: You can use truncate method to set non date fields to zero, e.g.:
Date input = new Date();
Date truncated = DateUtils.truncate(input, Calendar.DATE);
System.out.println(truncated);
Here's the maven dependency for Apache commons library.
You can get the "just the day, month, year by using the following code:
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class Answer {
public static void main(String args[]) throws ParseException {
// parse the date and time
String input = "Wed May 24 15:54:40 CEST 2017";
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
Date date = parser.parse(input);
// parse just the date
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
formatter.setTimeZone(TimeZone.getTimeZone("CEST"));
String formattedDate = formatter.format(date);
Date parsedDate = formatter.parse(formattedDate);
System.out.println(parsedDate);
// use https://currentmillis.com/ to check the milliseconds figures
System.out.println("Wed May 24 15:54:40 CEST 2017 in milliseconds \t" + date.getTime());
System.out.println("Wed May 24 00:00:00 CEST 2017 in milliseconds \t" + parsedDate.getTime());
}
}
The second SimpleDateFormat("yyyy-MM-dd"); parses on the year-month-day.
Use Date.getTime()); to get the milliseconds.
The output is:
Wed May 24 15:54:40 CEST 2017 in milliseconds 1495634080000
Wed May 24 00:00:00 CEST 2017 in milliseconds 1495584000000
1495584000000 = Wed May 24 2017 00:00:00 (using https://currentmillis.com/)
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.YEAR, 2017);
cal.set(Calendar.MONTH, 5 - 1);
cal.set(Calendar.DAY_OF_MONTH, 24);
cal.set(Calendar.MILLISECOND, 0);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
Date d = cal.getTime();
System.out.println(d.getTime());
this code creates a new java.util.Date with only year, month and day set. result of this example is 1495576800000 which is what you want.
A shorter way would be this:
Date d = new Date(0l);
d.setYear(117);
d.setMonth(4);
d.setDate(24);
d.setHours(0);
You should format the two dates:
Date date = new Date();
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd");
dt.format(date);
Then compare each other.

Calendar Sunday to Sunday

I'm trying to get flights for 8 days starting from Sunday to the next Sunday.
The way I have implemented it now is by displaying the 7 days starting the selected date from my form.
// set up calendar for sunday
Calendar sunday = Calendar.getInstance();
sunday.setTime(form.getDate());
sunday.add(Calendar.DAY_OF_WEEK, -1 * (sunday.get(Calendar.DAY_OF_WEEK) - 1));
//set up calendar for next saturday
Calendar saturday = Calendar.getInstance();
saturday.setTime(sunday.getTime());
saturday.add(Calendar.DAY_OF_WEEK, 7);
Since the max of DAY_OF_WEEK is 7, what do I need to use instead?
I tried changing this line:
saturday.add(Calendar.DAY_OF_WEEK, 7);
to the following one:
saturday.add(Calendar.DATE, 8);
I already tried couple changes but no luck.
Any advice?
Try using Calendar.DAY_OF_YEAR.
import java.text.*;
import java.util.*;
DateFormat dateFormat = new SimpleDateFormat("EEE, MMM dd, yyyy hh:mm:ss a z");
Calendar sunday = new GregorianCalendar();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY); // Set day of week to Sunday.
System.out.println(dateFormat.format(sunday.getTime()));
sunday.add(Calendar.DAY_OF_YEAR, 7); // Add seven days.
System.out.println(dateFormat.format(sunday.getTime()));
Output
Sun, Dec 04, 2016 11:47:32 PM EST
Sun, Dec 11, 2016 11:47:32 PM EST
You can create new calendar objects without modifying the existing one, by making a copy.
import java.text.*;
import java.util.*;
public class CalendarUtils {
public static void main(String[] args) {
Calendar sunday = CalendarUtils.getThisSundaysDate();
Calendar saturday = CalendarUtils.daysFrom(sunday, 6);
CalendarUtils.printDates(sunday, saturday);
}
public static Calendar getThisSundaysDate() {
Calendar sunday = new GregorianCalendar();
sunday.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
return sunday;
}
public static Calendar daysFrom(Calendar cal, int days) {
Calendar newCal = copyCalendar(cal);
newCal.add(Calendar.DAY_OF_YEAR, days);
return newCal;
}
public static Calendar copyCalendar(Calendar cal) {
Calendar copy = new GregorianCalendar();
copy.setTime(cal.getTime());
return copy;
}
public static void printDates(Calendar from, Calendar to) {
DateFormat dateFormat = new SimpleDateFormat("EEE, MMMM dd, yyyy hh:mm:ss a z");
System.out.println(dateFormat.format(from.getTime()));
System.out.println(dateFormat.format(to.getTime()));
}
}
If you're using Java 8, you should use the new java.time classes. In this case, you'd want to use the LocalDate class, and the TemporalAdjusters class, with it's previous(DayOfWeek) method.
Alternatively, use the previousOrSame(DayOfWeek), depending on what should happen if the reference date is a Sunday.
Example, using today as the reference date:
LocalDate refDate = LocalDate.now();
LocalDate prevSunday = refDate.with(TemporalAdjusters.previous(DayOfWeek.SUNDAY));
LocalDate nextSunday = prevSunday.plusDays(7);
DateTimeFormatter fmt = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL);
System.out.println("Ref. Date: " + refDate.format(fmt));
System.out.println("Prev. Sunday: " + prevSunday.format(fmt));
System.out.println("Next. Sunday: " + nextSunday.format(fmt));
Output
Ref. Date: Monday, December 5, 2016
Prev. Sunday: Sunday, December 4, 2016
Next. Sunday: Sunday, December 11, 2016

how to write date using tokenizer?

The following code here returns the date in the form "Day, Date, Month, Year".
The date currently entered in would return as Saturday 28 Dec 2013. However, I want to tokenize this and print the 4 parts out on 4 separate lines, starting with month, then date, then year, then day. What's the best way to do this?
import java.text.SimpleDateFormat;
import java.util.Date;
class Day{
public static void main( String[] args ){
SimpleDateFormat newDateFormat = new SimpleDateFormat("dd/MM/yyyy");
try {
Date myDate = newDateFormat.parse("28/12/2013");
newDateFormat.applyPattern("EEEE dd MMM yyyy");
String isDate = newDateFormat.format(myDate);
System.out.println(isDate);
} catch (Exception e) {
System.out.println("Error. Date is in the wrong format.");
}
}
}
use split() method :
String []myformat=isDate.split(" ");
System.out.println(myformat[2]);
System.out.println(myformat[1]);
System.out.println(myformat[3]);
System.out.println(myformat[0]);
use order whatever order you want.
I think this can solve your problem:
StringTokenizer tokenizer = new StringTokenizer(isDate, " ");
Map<String, String> dateParts = new HashMap<String, String>();
while(tokenizer.hasMoreElements()) {
dateParts.put("dayOfWeek", (String)tokenizer.nextElement());
dateParts.put("dayNumber", (String)tokenizer.nextElement());
dateParts.put("month", (String)tokenizer.nextElement());
dateParts.put("year", (String)tokenizer.nextElement());
}
System.out.println("Month: "+dateParts.get("month"));
System.out.println("Day of week: "+dateParts.get("dayOfWeek"));
System.out.println("Date: "+dateParts.get("dayNumber"));
System.out.println("Year: "+dateParts.get("year"));
use following code
Calendar cal = Calendar.getInstance();
cal.setTime(date);
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.MONTH));
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
I want to tokenize this and print the 4 parts out on 4 separate
lines, starting with month, then date, then year, then day. What's the
best way to do this?
You have Date Object you should better use Calendar to get as specific details as possible without formatting your date.
Note that problem with formatting and splitting is that in different format location of month, date and year will be different in String.
Which will not be the case in following code,
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String month = cal.getDisplayName(Calendar.MONTH, Calendar.SHORT, Locale.US);
int date_ = cal.get(Calendar.DAY_OF_MONTH);
int year = cal.get(Calendar.YEAR);
String day = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, Locale.US);
System.out.println(day);
System.out.println(date_);
System.out.println(month);
System.out.println(year);
OUTPUT
Tue
25
Aug
2015

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();

how to manipulate a Date object in java

I would like to take a date object like "Sat Feb 17 20:49:54 +0000 2007" and change the year variable to the current year dynamically to something like this "Sat Feb 17 20:49:54 +0000 2012" what would be the best way to do this in java?
Construct a Calendar from the Date, use the Calendar to set the year, and then get back a Date object from the Calendar.
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.YEAR, 2012);
date = c.getTime();
If that's already a date object, you can do this:
Calendar cal = Calendar.getInstance();
int currentYear = cal.get(Calendar.YEAR);
cal.setTime(dateObj);
//set the year to current year
cal.set(Calendar.YEAR, currentYear);
//new date object with current year
dateObj = cal.getTime();
If that's a string, you can parse the string to a Java Date object first using SimpleDateFormat:
http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
And the use the above calendar object.
Based on what you asked for, this is how you do that:
try {
DateFormat dateFormat = new SimpleDateFormat("E, dd MMM HH:mm:ss Z yyyy");
date = (Date) dateFormat.parse("Sat, Feb 17 20:49:54 +0000 2007");
Calendar cal = dateFormat.getCalendar();
cal.set(Calendar.YEAR, 2012);
} catch (ParseException pe) {
//ParseException Handling
} catch(Exception e) {
//Exception Handling
}
Another option would be to utilize JodaTime API
import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class App
{
public static void main( String[] args )
{
//Sat Feb 17 20:49:54 +0000 2007
DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd H:m:s Z yyyy");
DateTime dt = fmt.parseDateTime("Sat Feb 17 20:49:54 +0000 2007");
MutableDateTime mdt = dt.toMutableDateTime();
mdt.setYear(new DateTime().getYear());
System.out.println(fmt.print(mdt));
}
}

Categories

Resources