I have string of date with format like this: 19930508. I want to use only 0508 from this string which is MMdd and than compare it with today's MMdd.
The code i am using is:
Date todaysDate = new Date();
String dateTest = "19930508";
SimpleDateFormat df = new SimpleDateFormat("MMdd");
Date date = df.parse(dateTest);
String birthDate = df.format(date);
if(birthDate.equals(df.format(todaysDate))){do something}
The problem is the that birthdate formate is not working correctly neither todaysDate.
Date date var print nothing and birthDate string print 0220 which makes no sense to me.
Anyone with anyidea how can i work with this kind of formating and compare it with todaysdate ?
Using java.time from Java 8:
MonthDay now = MonthDay.now();
String dateTest = "19930508";
DateTimeFormatter yearMonthDayFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
MonthDay birthDay = MonthDay.parse(dateTest, yearMonthDayFormatter);
if (birthDay.equals(now)) {
System.out.println("same MMdd");
} else {
System.out.println("different MMdd");
}
// works with java6
public class AnniversaryChecker {
private final String dayInYear;
public AnniversaryChecker() {
this(new SimpleDateFormat("MMdd").format(new Date()));
}
// VisibleForTesting
public AnniversaryChecker(String mmdd) {
this.dayInYear = mmdd;
}
public boolean isAnniversary(String yyyyMMdd) {
return yyyyMMdd.endsWith(dayInYear);
}
}
Related
I have a string value which is equal to "202004". how can I convert it to "April, 2020" in Java?
I would use java.time for a task like this.
You can define two java.time.format.DateTimeFormatter instances (one for parsing the input string to java.time.YearMonth and another for formatting the obtained YearMonth to a string of the desired format).
Define a method like this one:
public static String convert(String monthInSomeYear, Locale locale) {
// create something that is able to parse such input
DateTimeFormatter inputParser = DateTimeFormatter.ofPattern("uuuuMM");
// then use that formatter in order to create an object of year and month
YearMonth yearMonth = YearMonth.parse(monthInSomeYear, inputParser);
/*
* the output format is different, so create another formatter
* with a different pattern. Please note that you need a Locale
* in order to define the language used for month names in the output.
*/
DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(
"MMMM, uuuu",
Locale.ENGLISH
);
// then return the desired format
return yearMonth.format(outputFormatter);
}
then use it, e.g. in a main method:
public static void main(String[] args) {
// your example input
String monthInAYear = "202004";
// use the method
String sameMonthInAYear = convert(monthInAYear, Locale.ENGLISH);
// and print the result
System.out.println(sameMonthInAYear);
}
The output will be this:
April, 2020
Use below one line code to format year month
int yearMonth = Integer.parseInt("202004");
String yearMonthStr = new DateFormatSymbols().getMonths()[(yearMonth % 10)-1] + ", "+yearMonth/100;
System.out.println(yearMonthStr);
Use DateFormatSymbols() class to implement the new date format from the string
String text="202011";
int num=0;
//Checking the last second character of the text for jan to sept month
if(text.charAt(text.length()-2)==0){
num=Integer.parseInt(""+text.charAt(text.length()-1))-1;
}
else {
num=Integer.parseInt(""+text.substring(text.length()-2))-1;
}
//Checking correct month value
if(num>=0&&num<=11){
String month = "";
DateFormatSymbols date_ = new DateFormatSymbols();
String[] month_name = date_.getMonths();
month = month_name[num];
System.out.println(month+","+text.substring(0,4));
}
else{
System.out.println("Wrong month value");
}
SimpleDateFormat oldFormat = new SimpleDateFormat("yyyyMM");
SimpleDateFormat newFormat = new SimpleDateFormat("MMMM, yyyy");
Date date = null;
try {
date = oldFormat.parse("202004");
} catch (ParseException e) {
e.printStackTrace();
}
String newDateString = newFormat.format(date);
SimpleDateFormat documentation
Let try my code snippet:
SimpleDateFormat inSdf = new SimpleDateFormat("yyyyMM");
Date date = inSdf.parse("202112");
SimpleDateFormat outSdf = new SimpleDateFormat("MMMM, yyyy");
String sDate = outSdf.format(date);
System.out.println(sDate);
Result:
December, 2021
I need to parse string value of data = "2013-12-09 12:14:09.994844+10" with SimpleDateFormat.
I'm using format = "yyyy-MM-dd HH:mm:ss.SSSSSSZ", but it's not working.
How can I solve this problem?
public class Test {
public static final String FORMAT1 = "hh:mm aa dd.MM.yyyy";
public static final String FORMAT2 = "yyyy-MM-dd HH:mm:ss.SSSSSSZ";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Time = "
+ getDate("2013-12-09 12:14:09.994844+10",
DateTimeUtils.FORMAT2, DateTimeUtils.FORMAT1));
}
public static String getDate(String inputDate, String inputFormat,
String outputFormat) {
String strDate = "";
SimpleDateFormat sdfInput = new SimpleDateFormat(inputFormat,
Locale.getDefault());
SimpleDateFormat sdfOutput = new SimpleDateFormat(outputFormat,
Locale.getDefault());
if (inputDate != null) {
Date date;
try {
date = sdfInput.parse(inputDate);
strDate = sdfOutput.format(date);
} catch (ParseException e) {
strDate = "";
e.printStackTrace();
}
}
return strDate.toUpperCase();
}
}
In Java SE 7 to format a timezone with one sign and two digits use the letter 'X'. For example: "yyyy-MM-dd HH:mm:ss.SSSSSSX". The javadoc can be found here.
In Android however the letter 'X' is not supported but you may add two extra zeros to the date string in order to use 'Z'. For example: "2013-12-09 12:14:09.994844+1000" will be correctly parsed. The javadoc for Android can be found here.
SimpleDateFormat can't deal with microseconds.
You need to strip out the extra 3 digits.
like this:
data = data.substring(0, data.length()-4)+"Z";
I'm like two days on this problem. This is in continuation from this question: convert string to joda datetime gets stuck
I am trying to perform one simple task, to take SQL SERVER ISO 8601 string and convert it to DateTime or LocalDate. I tried everything, but when it comes to the actual conversion with the debugger the program cursor just goes for thinking and never comes back, i.e., the program is stuck there.
I'm so desperate that I even tried to convert that String to Date (which works!) and then convert that Date to DateTime or LocalDate. All had the same result, on the line of the conversion the program looks like stuck in some endless loop (and the fan starts working like crazy).
Here is my so simple function:
public static LocalDate SQLServerIso8601StringToLocalDate(String date) {
LocalDate dateToReturn = null;
DateFormat df = new SimpleDateFormat(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT);
try {
Date tempDate = (Date) df.parse(date);
DateTime dt = new DateTime(tempDate);
dateToReturn = new LocalDate(tempDate);
} catch (ParseException e) {
// strToReturn = strSqlDate;
}
return dateToReturn;
/*
date = date.replace('T', ' ');
return SimpleIso8601StringToDateTime(date);
*/
//return LocalDate.parse(date, DateTimeFormat.forPattern(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT));
/* DateTimeFormatter df = DateTimeFormat.forPattern(CONSTS_APP_GENERAL.SQL_SERVER_DATE_FORMAT_WITH_TZ);
return df.parseDateTime(date);
*/ }
This is my String: 2014-01-01T00:00:00
also:
public static final String SQL_SERVER_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss";
Any ideas?
public static Date getDateFromString(String format, String dateStr) {
DateFormat formatter = new SimpleDateFormat(format);
Date date = null;
try {
date = (Date) formatter.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Is it possible to do format a date of type String using a date formatter? I want to store my Date and Time in the Event class as Strings so that I don't need to convert the Strings loaded from a MYSQL database (using the types DATE and TIME) back into Date types so they can be stored in new Event objects. MySQL only accepts DATE in the format of YYYY-MM-DD and TIME in the format of HH:MM:SS but i want these to be formatted differently when i go to print them out in my program.
When i run this code i get an Cannot format given Object as a Date at java.text.DateFormat.format(Unknown Source) error. If i try using parse() it won't compile because it only accepts Dates.
Main class
public Main() {
ArrayList<Event> events = new ArrayList<Event>();
private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:MM:SS");
private SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD");
//Stores current time and date
Date date;
Date time;
String d = "";
String t = "";
d= dateFormat.parse(date);
t= timeFormat.parse(time);
events.add(d, t);
//Print out newly formatted date and time when loaded from mysql
System.out.println(events.get(0).printDate());
System.out.println(events.get(0).printTime());
}
Events class
public class Event {
private String date;
private String time;
public Event(String d, String t) {
date = d;
time = t;
}
public String printDate() {
SimpleDateFormat format = new SimpleDateFormat("DD/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
public String printTime() {
SimpleDateFormat format = new SimpleDateFormat("HH:mm");
String newTime = format.format(time);
return newTime;
}
}
In Event, you should use Date type for date and time field.
This is a more appropriate representation for date and time value. And with them, you can use DateFormat to do whatever formatting you want
(It will be even better to use Joda time LocalDate and LocalTime for your date and time, but that's a bit off topic)
You can't format your dates because they are String objects and SimpleDateFormat needs Date objects.
You should consider a different way of storing them (either as Date or Calendar). See below:
public class Event
{
private Date date;
private Date time;
public Event(String d, String t)
{
String[] details = d.split("\\-");
Calendar c = Calendar.getInstance();
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
date = c.getTime();
details = t.split(":");
c.set(Integer.parseInt(details[0]), Integer.parseInt(details[1]), Integer.parseInt(details[2]));
time = c.getTime();
}
public String printDate()
{
SimpleDateFormat format = new SimpleDateFormat("dd/MM/YYYY");
String newDate = format.format(date);
return newDate;
}
// rest of you class can stay the way it is
}
You can format java.util.Date or java.sql.Date (which is subclass of java.util.Date) using date formatter, eg:
DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
String dateStr = df.format(date);
Using jdbc ResultSet getDate() method you can obtain java.sql.Date object which you can print in any format using method above
Similar techniques can also be used to parse string in any format into a java.util.Date object
Date date = df.parse(dateStr);
Check the javadoc for the right formatting codes. Try this:
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
Good Day.
I've got another problem related to Jtable.
I want to change the row color of a table if the date inside column (expiry) exceeds or is equal to the current date.
I tried this code but i get an error: java.lang.NumberFormatException: For input string: "2012-03-15"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String expDateString = sdf.format(cal.getTime());
System.out.println(expDateString);
Double date = Double.parseDouble(expDateString);
Double val = Double.parseDouble(tableSummary.getModel().getValueAt(row, 6).toString());
for(int i=0; i<=tableSummary.getRowCount()-1; i++){
if(val >= date){
renderer.setBackground(red);
}
}
Thanks!
here's a new code:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String expDateString = sdf.format(cal.getTime());
Date today = new Date(expDateString);
System.out.println("ang churva is " + today);
Date given = new Date(tableSummary.getModel().getValueAt(row, 6).toString());
for(int i=0; i<=tableSummary.getRowCount()-1; i++){
if(today.compareTo(given)>=0){
renderer.setBackground(red);
}
}
but i get this exception: java.lang.IllegalArgumentException at Date today = new Date(expDateString);
Use the code
DATEDIFF('d',NOW(),exdate)
in your resultset query. It will return the difference. Alter it possibly to match your needs.
You can't cast a date string in a double
Double date = Double.parseDouble(expDateString); //does not work!
Simple example of how you can compare you dates. Note that if the objects in your JTable already are Dates, you don't need all the parsing, which would make your life easier.
The output of the code below is:
expiryDate=2012-03-15
tableDateOK=2012-03-12
tableDateExpired=2012-03-18
tableDateOK>expiryDate = false
tableDateExpired>expiryDate = true
Code:
public static void main(String args[]) throws ParseException {
String expiryDate = "2012-03-15";
String tableDateOk = "2012-03-12";
String tableDateExpired = "2012-03-18";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("expiryDate="+expiryDate);
System.out.println("tableDateOK="+tableDateOk);
System.out.println("tableDateExpired="+tableDateExpired);
System.out.println("tableDateOK>expiryDate = " + sdf.parse(tableDateOk).after(sdf.parse(expiryDate)));
System.out.println("tableDateExpired>expiryDate = " + sdf.parse(tableDateExpired).after(sdf.parse(expiryDate)));
}
line Double date = Double.parseDouble(expDateString);
this cannot work because string "2012-03-15" is simply not a valid double value.
I do not understand why you are trying to compare two double values:
if you have Date in table, use Date.after() and Date.before() to find out, whether your date is before or after now.
if you have String in table, use the SimpleDateFormat.parse() to get Date from it and do point 1
public String compareDate( Request request ) throws ParseException {
Date debitDate= request.getPaymentTxn().getCrValDt();
Date now = new Date();
String response="";
SimpleDateFormat sdfDate = new SimpleDateFormat("dd/MM/yyyy");
String strCurrDate = sdfDate.format(now);
String strDebitDate = sdfDate.format(debitDate);
System.out.println("Current Date: " + strCurrDate);
Date currentDate = new SimpleDateFormat("dd/MM/yyyy").parse(strCurrDate);
Date txnDate = new SimpleDateFormat("dd/MM/yyyy").parse(strDebitDate);
System.out.println("C -> "+currentDate);
System.out.println("C -> "+txnDate);
if (txnDate!=null){
if (currentDate.equals(txnDate))
{
System.out.println("Valid Txn");
response="valid";
}
if (currentDate.after(txnDate))
{
System.out.println("--> Not Valid TXN Past");
response="notValid";
}
if (currentDate.before(txnDate)){
System.out.println("Future Valid TXn");
response="future";
}
}
return response;
}
PLease Chk it out its working fine