can any help, how to get the right date from an String like this "2014-01-10T09:41:16.000+0000"
my code is:
String strDate = "2014-01-10T09:41:16.000+0000";
String day = "";
String format = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
Locale locale = new Locale("es", "ES");
SimpleDateFormat formater = new SimpleDateFormat(format, locale);
formater.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));
Calendar cal = Calendar.getInstance();
try {
cal.setTimeInMillis(formater.parse(strDate).getTime());
String offerDate = cal.get(Calendar.DAY_OF_MONTH) + "-" + cal.get(Calendar.MONTH) + "-" + cal.get(Calendar.YEAR);
System.out.println(offerDate);
} catch (Exception e){
System.out.println(e.getMessage());
}
in the result i give something like this: "10-0-2014", i want the result like that "10-01-2014"
thanks in advance :)
The documentation states:
java.util.Calendar.MONTH
MONTH public static final int MONTH Field number for get and set
indicating the month. This is a calendar-specific value. The first
month of the year in the Gregorian and Julian calendars is JANUARY
which is 0; the last depends on the number of months in a year.
-> Counting starts at 0 for Calendar.MONTH
I think the easiest would be to use another formatter object to do the formatting instead of building it yourself:
try {
Date d = new Date(cal.setTimeInMillis(formater.parse(strDate).getTime()));
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
String offerDate = format.format(d);
System.out.println(offerDate);
} catch (Exception e){
System.out.println(e.getMessage());
}
Related
I have to accept a date from a user via a simple inputText field (JSF 2). I created a Converter so I can validate the date and now I am running into trouble with 1, 3, and 5+ digit years. All dates entered by the user will be either today or in the future (up to a reasonable maximum).
The below solution accepts three different date formats and will correctly handle 2 and 4 digit years (in the former case by using set2DigitYearStart to convert them to 20XX). I am completely stumped how I can handle other wrong dates.
Code
public static void main(String[] args) throws Exception {
String date = "2/3/111"; // This should be rejected!
List<String> datePatterns = new ArrayList<String>();
datePatterns.add("MM-dd-yy");
datePatterns.add("MM.dd.yy");
datePatterns.add("MM/dd/yy");
for (String pattern : datePatterns) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.set2DigitYearStart(new SimpleDateFormat("MM/dd/yyyy").parse("1/1/2000"));
formatter.setLenient(false);
try {
System.out.println(formatter.parse(date));
break;
} catch (ParseException ignore) {
System.out.println("Date format doesn't match pattern: " + pattern);
}
}
}
Examples That Should be Accepted
02/02/02
02/02/2002
Examples That Should be Rejected
02/02/1
02/02/333
02/02/55555
One Approach
Get some theoretical maxDate and yesterday's date, then compare the output. This seems wrong somehow, though...
SimpleDateFormat f4 = new SimpleDateFormat("MM/dd/yyyy");
Date maxDate = f4.parse("01/01/2099");
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
Date minDate = f4.parse(dateFormat.format(cal.getTime()));
Add some specific validation after your parsing is finished to reject any years that are out of range ie getYear() < 1000 and getYear() > 9999
Warning this code is not compiled or tested as I am typing on a tablet.
String dateStr = "2/3/111"; // This should be rejected!
List<String> datePatterns = new ArrayList<String>();
datePatterns.add("MM-dd-yy");
datePatterns.add("MM.dd.yy");
datePatterns.add("MM/dd/yy");
Date date = null;
for (String pattern : datePatterns) {
SimpleDateFormat formatter = new SimpleDateFormat(pattern);
formatter.set2DigitYearStart(new SimpleDateFormat("MM/dd/yyyy").parse("1/1/2000"));
formatter.setLenient(false);
try {
date = dateformatter.parse(dateStr));
break;
} catch (ParseException ignore) {
continue;
}
}
if (date != null) {
Calendar cal = new GregorianCalendar (date);
int year = cal.get(Calendar.YEAR);
if (year() < 1000 || year() > 9999) {
System.out.println("Date format doesn't match pattern: "
+ datePatterns);
}
} else {
System.out.println("Date format doesn't match pattern: "
+ datePatterns);
{
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).
I haven't programmed in Java for many years, but I now have to change a program I wrote some time ago. In this program I need to read a QIF file and find the qif record with the maximum date (Dmm-dd-yyyy).
I could not get this to work in my program so I wrote a simple test to demonstrate the problem I am having. I think there are other ways to do this, like lists and collections. But I still want to know why using SimpleDateFormat won't work. Notice in the output that this method produces the max for July but seems to ignore all August dates.
Thanks, Mike
import java.text.SimpleDateFormat;
import java.util.Date;
class DateParser {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
Date nextDate = null;
Date maxDate = null;
String nextStrDate = null;
String maxStrDate = null;
//Fill date array.
String date[] = {"07-14-2014","07-22-2014","07-31-2014",
"08-01-2014","08-04-2014","08-06-2014"};
try {
//Start with early maximum date.
maxDate = sdf.parse("01-01-1800");
// Find Max date in array.
for (int i=0; i<6; ++i) {
nextStrDate = date[i];
nextDate = sdf.parse(nextStrDate);
if(nextDate.after(maxDate)){
maxStrDate = nextStrDate;
maxDate = nextDate;
}
System.out.println( "Next Date = " + nextStrDate);
}
System.out.println("\nMax Date = " + maxStrDate);
} catch (Exception e) {
System.out.println("Got error:" + e);
}
}
}
OUTPUT
Next Date = 07-14-2014
Next Date = 07-22-2014
Next Date = 07-31-2014
Next Date = 08-01-2014
Next Date = 08-04-2014
Next Date = 08-06-2014
Max Date = 07-31-2014
From the Java Docs....
m Minute in hour
What you want is
M Month in year
Change mm-dd-yyyy to MM-dd-yyyy
You format is incorrect, this
SimpleDateFormat sdf = new SimpleDateFormat("mm-dd-yyyy");
should be
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yyyy");
because (per the SimpleDateFormat documentation),
Letter Date or Time Component Presentation Examples
...
M Month in year Month July; Jul; 07
...
m Minute in hour Number 30
I have the following function to convert date:
public String dateConvert(String D){
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-DD");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MMMM-yyyy");
Date date = null;
try {
date = format1.parse(D);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String dateString = format2.format(date);
dateString = dateString.replace("-", " ");
System.out.println(dateString);
return ((dateString));
}
However what ever date I pass to this, the month is always converted to January. I cant understand where I am going wrong!
Uppercase D is the day of the year, not the day of the month.
If you take any day of the month (1-31) and treat it as the day of the year, it will fall in January.
Use lowercase d for format1.
Here
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd"); // this was incorrect.
Otherwise, it seems to work fine here.
public static void main(String[] args) {
dateConvert("2013-10-12");
}
Prints
12 October 2013
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());
}
}