how to write date using tokenizer? - java

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

Related

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

I want my string to converted to a day [duplicate]

This question already has answers here:
How to determine day of week by passing specific date?
(28 answers)
Closed 7 years ago.
I have this string
String s = "29/04/2015"
And I want it to produce the name of that day in my language, which is Norwegian.
For example:
29/04/2015 is "Onsdag"
30/04/2015 is "Torsdag"
How can I do this?
String dateString = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(dateString);
SimpleDateFormat formatter = new SimpleDateFormat("E", Locale.no_NO);
String day = formatter.format(date);
Now day will have the day in given locale. Update
You need to configure an instance of DateFormat, with your locale, (take a look at https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html).
then parse the Date and get the day, as Dilip already suggests.
You can use date parsing combined with Locale settings to get the desired output. For e.g. refer following code.
String dateStr = "29/04/2015";
SimpleDateFormat dtf = new SimpleDateFormat("dd/MM/yyyy");
Date dt = dtf.parse(dateStr);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
String m = cal.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG_FORMAT, new Locale("no", "NO"));
System.out.println(m);
For more information about locale, visit Oracle Java Documentation.
First you will need to parse the String to a Date. Then use a Calendar to get the day of the week. You can use an array to convert it to the appropriate string.
// Array of Days
final String[] DAYS = {
"søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"
};
// Parse the date
final String source = "27/04/2015";
final DateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
try {
date = format.parse(source);
} catch (final ParseException e) {
e.printStackTrace();
}
// Convert to calendar
final Calendar c = Calendar.getInstance();
c.setTime(date);
final int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
// Get the day's name
System.out.println("Day of Week: " + dayOfWeek);
System.out.println("Day = " + DAYS[dayOfWeek - 1]);
You need to parse your text with date to Date instance and then format it back to text. You can do it with SimpleDateFormat class which supports many patterns of dates like
dd/MM/yyyy for your original date,
and EEEE for full name of day in month.
While formatting you will also need to specify locale you want to use. To create Norway specific locale you can use for instance
Locale nor = Locale.forLanguageTag("no-NO");
So your code can look more or less like:
String text = "29/04/2015";
Locale nor = Locale.forLanguageTag("no-NO");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy", nor);
SimpleDateFormat dayOfWeek = new SimpleDateFormat("EEEE", nor);
Date date = sdf.parse(text);
System.out.println(dayOfWeek.format(date));
Output: onsdag.
final int SUNDAY = 1;
final int ONSDAG = 2;
final int TORSDAG = 3;
....
....
String s = "29/04/2015";
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Date date = dateFormat.parse(s);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int day = calendar.get(Calendar.DAY_OF_WEEK);
String dayString;
switch (day) {
case(ONSDAG):
dayString = "ONSDAG";
break;
....
}
EDIT: I just tested this and it actually starts from Sunday, and returns the value of 1 for sunday, I've changed the constant values to reflect this.
First you'll need a Calendar object.
Calendar cal = Calendar.getInstance();
String s = "29/04/2015"
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
cal.setTime(format.parse(s));
From the Calendar you can get the day of the week.
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
dayOfWeek will be 1-7 with Sunday (in english) being 1
You can use an HashMap map where the first parametri is the date "29/4/2015" while the second is the meaning. You can use your string to get the meaning map.get (yourString).

find out the date from an input string

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

How to get last month/year in java?

How do I find out the last month and its year in Java?
e.g. If today is Oct. 10 2012, the result should be Month = 9 and Year = 2012. If today is Jan. 10 2013, the result should be Month = 12 and Year = 2012.
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
java.time
Using java.time framework built into Java 8:
import java.time.LocalDate;
LocalDate now = LocalDate.now(); // 2015-11-24
LocalDate earlier = now.minusMonths(1); // 2015-10-24
earlier.getMonth(); // java.time.Month = OCTOBER
earlier.getMonth.getValue(); // 10
earlier.getYear(); // 2015
Use Joda Time Library. It is very easy to handle date, time, calender and locale with it and it will be integrated to java in version 8.
DateTime#minusMonths method would help you get previous month.
DateTime month = new DateTime().minusMonths (1);
you can use the Calendar class to do so:
SimpleDateFormat format = new SimpleDateFormat("yyyy.MM.dd HH:mm");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
System.out.println(format.format(cal.getTime()));
This prints : 2012.09.10 11:01 for actual date 2012.10.10 11:01
The simplest & least error prone approach is... Use Calendar's roll() method. Like this:
c.roll(Calendar.MONTH, false);
the roll method takes a boolean, which basically means roll the month up(true) or down(false)?
YearMonth class
You can use the java.time.YearMonth class, and its minusMonths method.
YearMonth lastMonth = YearMonth.now().minusMonths(1);
Calling toString gives you output in standard ISO 8601 format: yyyy-mm
You can access the parts, the year and the month. You may choose to use the Month enum object, or a mere int value 1-12 for the month.
int year = lastMonth.getYear() ;
int month = lastMonth.getMonthValue() ;
Month monthEnum = lastMonth.getMonth() ;
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
You need to be aware that month is zero based so when you do the getMonth you will need to add 1. In the example below we have to add 1 to Januaray as 1 and not 0
Calendar c = Calendar.getInstance();
c.set(2011, 2, 1);
c.add(Calendar.MONTH, -1);
int month = c.get(Calendar.MONTH) + 1;
assertEquals(1, month);
You get by using the LocalDate class.
For Example:
To get last month date:
LocalDate.now().minusMonths(1);
To get starting date of last month
LocalDate.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth());
Similarly for Year:
To get last year date:
LocalDate.now().minusYears(1);
To get starting date of last year :
LocalDate.now().minusYears(1).with(TemporalAdjusters.lastDayOfYear());
Here's the code snippet.I think it works.
Calendar cal = Calendar.getInstance();
SimpleDateFormat simpleMonth=new SimpleDateFormat("MMMM YYYY");
cal.add(Calendar.MONTH, -1);
System.out.println(simpleMonth.format(prevcal.getTime()));

Date function in java

I have two dates
1) from_date: eg. 01/01/2010 (1st January 2010)
2) present_date: eg. 05/06/2011 (5th June 2011)
I want the third date as:
3) req_date: eg. 01/01/2011(1st January 2011)
Year should come from "present_date" and day and month should come from "from_date".
The dates which I mentioned are hardCoded.
In my code, I run a query to get these 2 dates.
Look into the Calendar class
http://www.java-examples.com/add-or-substract-days-current-date-using-java-calendar
Something like // Untested
Calendar cal=Calendar.getInstance();
cal.setTime(from_date);
Calendar cal2=Calendar.getInstance();
cal2.setTime(present_date);
Calendar cal3=Calendar.getInstance();
cal3.set(cal2.get(CALENDAR.YEAR),cal1.get(CALENDAR.MONTH),cal1.get(CALENDAR.DATE));
Date reg_date = cal3.getTime();
You can set individual fields of dates:
Date req_date = from_date;
req_date.setYear (present_date.getYear());
Or, if you're using Calendar (Date is deprecated):
Calendar req_date = from_date;
req_date.set (YEAR, present_date.get(YEAR));
If they're strings, you can just use substringing to get what you want:
String req_date = from_date.substring(0,6) + present_date.substring(6);
(assuming XX/XX/YYYY as seems to be the case).
Not sure if I understand you correctly but this example should get you started:
int year = 2003;
int month = 12;
int day = 12;
String date = year + "/" + month + "/" + day;
java.util.Date utilDate = null;
try {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
utilDate = formatter.parse(date);
System.out.println("utilDate:" + utilDate);
} catch (ParseException e) {
System.out.println(e.toString());
e.printStackTrace();
}
this way you can convert date Strings to java.util.Date object, then you can construct the third date by using Date/Calendar methods
from_date: for EX. 01/01/2010 (1 st January 2010)
present_date :for EX. 05/06/2011(5th june 2011)
String s1[]=from_date.split("/");
String s2[]=present_date.split("/");
String newDate=s1[0]+"/"+s1[1]+"/"+s2[2];
import java.util.Date;
public class DateDemo {
public static void main(String args[]) {
Date date = new Date();
System.out.println(date.toString());
}
}

Categories

Resources