When I create a Date from parsing a String and access the day of the month, I get the wrong value.
Date datearr = null;
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
String dataa = "17-03-2012";
try {
datearr = df1.parse(dataa);
} catch (ParseException e) {
Toast.makeText(this, "err", 1000).show();
}
int DPDMonth = datearr.getMonth() + 1;
int DPDDay = datearr.getDay();
int DPDYear = datearr.getYear() + 1900;
System.out.println(Integer.toString(DPDDay)+"-"+Integer.toString(DPDMonth)+"-"+Integer.toString(DPDYear));
Why do I get 0 instead of 17?
03-11 10:24:44.286: I/System.out(2978): 0-3-2012
Here's a snippet the doesn't use deprecated methods anymore, fixes naming issues and simplifies the output.
Date datearr = null;
DateFormat df1 = new SimpleDateFormat("dd-MM-yyyy");
String dataa = "17-03-2012";
try {
datearr = df1.parse(dataa);
} catch (ParseException e) {
Toast.makeText(this, "err", 1000).show();
return; // do not continue in case of a parse problem!!
}
// "convert" the Date instance to a Calendar
Calendar cal = Calendar.getInstance();
cal.setTime(datearr);
// use the Calendar the get the fields
int dPDMonth = cal.get(Calendar.MONTH)+1;
int dPDDay = cal.get(Calendar.DAY_OF_MONTH);
int dPDYear = cal.get(Calendar.YEAR);
// simplified output - no need to create strings
System.out.println(dPDDay+"-"+dPDMonth+"-"+dPDYear);
You should use
int DPDDay = datearr.getDate();
getDay() return a day in week
This kind of work is much easier when using the third-party library, Joda-Time 2.3.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;
String dateString = "17-03-2012";
DateTimeFormatter formatter = DateTimeFormat.forPattern( "dd-MM-yyyy" );
DateTime dateTime = formatter.parseDateTime( dateString ).withTimeAtStartOfDay();
int dayOfMonth = dateTime.getDayOfMonth();
Related
I am trying to parse date strings, my problem is that those strings can have different dateformats depends on if they talk about today, tomorrow or another day.
If they talk about today event the format is like this: 20:45
If they talk about tomorrow event the format is: tomorrow 20: 45
And if they talk about another day the format is: May 10 2016
So I would like to know if I can parse the three of them with the same DateFormat, if not what will be the best way.
DateFormat format = new SimpleDateFormat("EEEE d ' de' MMMM ' de' yyyy", locale);
You cant use the same SimpleDateFormat to parse all types, and wont be a good practice neither, not readable and more complex not adding any special value, i would try something like this:
private static final SimpleDateFormat formatHHMM = new SimpleDateFormat("hh:mm");
private static final SimpleDateFormat formatOther = new SimpleDateFormat("MMM dd yyyy");
private static String convertDate(Date curDate) {
if (isToday(curDate)) {
return formatHHMM.format(curDate);
}
else if (isTomorrow(curDate)) {
return "Tomorrow " + formatHHMM.format(curDate);
}
return formatOther.format(curDate);
}
private static boolean isToday(Date curDate) {
Date today = Calendar.getInstance().getTime();
return today.equals(curDate);
}
private static boolean isTomorrow(Date curDate) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1);
Date tomorrow = calendar.getTime();
return tomorrow.equals(curDate);
}
//Check the code with this
public static void main( String[] args )
{
Date curDate = new Date();
System.out.println( convertDate(curDate));
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1);
Date tomorrow = calendar.getTime();
System.out.println( convertDate(tomorrow));
calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 15);
Date other = calendar.getTime();
System.out.println( convertDate(other));
}
I don't think it's possible to parse the 3 formats with the same formatter. Although it may be possible to parse the first two with only one formatter, the difference of meaning (today or tomorrow) would imply a different logic, which can't be obtained with a single formatter.
I suggest you to handle each case separately, trying one after another:
try {
return LocalDate
.now()
.atTime(LocalTime.parse(date));
} catch (DateTimeParseException e) {
try {
return LocalDate
.now()
.plusDays(1)
.atTime(LocalTime.parse(date, DateTimeFormatter.ofPattern("'tomorrow' HH:mm")));
} catch (DateTimeParseException e1) {
return LocalDate
.parse(date, DateTimeFormatter.ofPattern("MMMM dd yyyy", Locale.ENGLISH))
.atStartOfDay();
}
}
I'm not sure about the clarity of the control flow, though. If the the number of input formats grows, a refactor into something clearer may be required.
if (DateFormat.charAt(0).isDigit() && DateFormat.charAt(1).isDigit() && DateFormat.charAt(2).isLetterOrDigit()==false .... {
new String SimpleDateFormat= '15.03.2016';
else {
if (DateFormat.charAt(0).isLetter('t') && DateFormat.charAt(1).isLetter('o') && and so on
{ SimpleDateFormat='16.03.2016'
and you may change the condition on 1 by 1 character to match all your type of data formats
This question already has answers here:
Java string to date conversion
(17 answers)
Closed 8 years ago.
How can I get day and date from given Strings. For example:
String date="25-12-2014";
How to get date and day from given string?
Expected output is,
25
Thu
I got stuck when I tried this.
private static String getFormatedDate(String strDate) {
String result = "";
if(strDate != null) {
if (strDate.contains("-")) {
String[] dates = strDate.split("-");
for(int i=0;i<dates.length;i++) {
result = result + Utils.replaceDateFormat(dates[i].trim(),"MMM dd", "EE, M.dd") + ("-");
}
int lastIndex = result.lastIndexOf("-");
result = result.substring(0, lastIndex).trim();
}
else {
result = Utils.replaceDateFormat(strDate.trim(),"MMM dd", "EE, M.dd");
}
}
return result;
}
Utils:
public static String replaceDateFormat(String value, String actualFormat, String exceptedFormat) {
final int currentYear = Calendar.getInstance().get(Calendar.YEAR);
final SimpleDateFormat fromDate = new SimpleDateFormat(actualFormat);
final SimpleDateFormat toDate = new SimpleDateFormat(exceptedFormat);
Date convertedFromDate = null;
try {
convertedFromDate = fromDate.parse(value);
} catch (java.text.ParseException e) {
e.printStackTrace();
}
final Calendar c1 = Calendar.getInstance();
c1.setTime(convertedFromDate);
c1.set(Calendar.YEAR, currentYear);
return toDate.format(c1.getTime());
}
Your methods are very convoluted for a relatively simple task. Why don't you use SimpleDateFormat? You can use the parse method. For example:
Date date = new SimpleDateFormat("dd-MM-yyyy").parse(string);
And then you can get the required fields from there.
EDIT
To get the day of the week, you were right with this code:
Date d = date.parse(result);
Calendar c = Calendar.getInstance();
c.setTime(d);
int day=c.get(Calendar.DAY_OF_WEEK);
And then if you want it in the format above, you could just make an array filled with the days of the week:
String[] daysOfWeek = new String[]{"Sun","Mon"... etc}
String day = daysOfWeek[day - 1];
You can use the method from Calendar:
String date = "25-12-2014";
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(format.parse(date));
int day = cal.get(Calendar.DAY_OF_MONTH);
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK);
DateFormatSymbols symbols = new DateFormatSymbols(new Locale("en"));
String[] days = symbols.getShortWeekdays();
System.out.printf("%02d %3s\n", day, days[dayOfWeek]);
The symbols can be set to your Locale zone.
if you are allowed to use java 8 you can give LocalDate a chance:
String date = "25-12-2014";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy");
LocalDate ld = LocalDate.parse(date, formatter);
System.out.println(ld.getDayOfMonth() + ", " + ld.getDayOfWeek());
Output is:
25, THURSDAY
EDIT:
System.out.println(ld.getDayOfMonth() + ", " + ld.getDayOfWeek().substring(0, 3));
#No aNoNym suggestion is right, with the following you get
25, THU
I need to convert a string in the format "dd/mm/yyyy", to a long type. In order to pass the value to the calendarProvider in android.
Currently I have:
Calendar calendar = Calendar.getInstance();
long startEndDate = 0;
Calendar currentDateInfo = Calendar.getInstance();
currentDateInfo.set(calendar.get(Calendar.YEAR), calendar.SEPTEMBER, calendar.get(Calendar.DAY_OF_MONTH));
startEndDate = currentDateInfo.getTimeInMillis();
I need:
long startDate = *Some sort of conversion* EditText.getText();
I've tried using SimpleDateFormat but i'm having problems getting the correct type back. Any help would be much appreciated.
You can use the following code to get a long value (milliseconds since January 1, 1970, 00:00:00 GMT) from a String date with the format "dd/mm/yyyy".
try {
String dateString = "30/09/2014";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date date = sdf.parse(dateString);
long startDate = date.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
Use like this your code
String[] dateArray = dateString.split("-");
int year = Integer.parseInt(dateArray[0]);
int month = Integer.parseInt(dateArray[1]);
int date = Integer.parseInt(dateArray[2]);
GregorianCalendar gc = new GregorianCalendar(year,month,date);
long timeStamp = gc.getTimeInMillies();
Well i am trying to define a date and see the difference with recent date in seconds.
Below is the code i did inside onCreate method of activity:
txtNowTime = (TextView)findViewById(R.id.textViewNow);
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String currentDateandTime = formata.format(new Date());
#SuppressWarnings("deprecation")
Date oldd = new Date("07/18/2014 11:12:13");
String olddt_frmt = formata.format(oldd);
long diff =0;
try {
Date d_recent = formata.parse("currentDateandTime");
diff = d_recent.getTime() - oldd.getTime();
} catch (ParseException ex) {
ex.printStackTrace(); }
txtNowTime.setText(String.valueOf(diff));
But its not showing any result. :-(
Change this
Date d_recent = formata.parse("currentDateandTime"); to Date d_recent = formata.parse(currentDateandTime);
please find the answer
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault());
String currentDateandTime = formata.format(new Date());
long diff = 0;
try {
Date d_recent = formata.parse(currentDateandTime);
Date olddt_frmt = formata.parse("07/18/2014 11:12:13");
diff = d_recent.getTime() - olddt_frmt.getTime();
} catch (ParseException ex) {
ex.printStackTrace();
}
See this similar question using Joda-Time. Or use the new java.time package in Java 8. The old java.util.Date and .Calendar class's are notoriously troublesome and should be avoided.
Joda-Time
DateTime then = DateTime.now();
//…
DateTime now = DateTime.now();
Seconds seconds = Seconds.secondsBetween( now, then );
int secondsElapsed = seconds.getSeconds();
I have a question related to conversion/formatting of date.
I have a date,say,workDate with a value, eg: 2011-11-27 00:00:00
From an input textbox, I receive a time value(as String) in the form "HH:mm:ss", eg: "06:00:00"
My task is to create a new Date,say,newWorkDate, having the same year,month,date as workDate,and time to be the textbox input value.
So in this case, newWorkDate should be equal to 2011-11-27 06:00:00.
Can you help me figure out how this can be achieved using Java?
Here is what I have so far:
SimpleDateFormat df = new SimpleDateFormat("HH:mm:ss");
//Text box input is converted to Date format -what will be the default year,month and date set here?
Date textBoxTime = df.parse(minorMandatoryShiftStartTimeStr);
Date workDate = getWorkDate();
int year = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(0, 4));
int month = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(4, 6));
int date = Integer.parseInt(DateHelper.getYYYYMMDD(workDate).substring(6, 8));
Date newWorkDate = DateHelper.createDate(year, month, day);
//not sure how to set the textBox time to this newWorkDate.
[UPDATE]: Thx for the help,guys!Here is the updated code based on all your suggestions..Hopefully this will work.:)
String[] split = textBoxTime.split(":");
int hour = 0;
if (!split[0].isEmpty)){
hour = Integer.parseInt(split[0]);}
int minute = 0;
if (!split[1].isEmpty()){
minute = Integer.parseInt(split[1]);}
int second = 0;
if (!split[2].isEmpty()){
second = Integer.parseInt(split[2]);}
Calendar cal=Calendar.getInstance();
cal.setTime(workDate);
cal.set(Calendar.HOUR, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, second);
Date newWorkDate = cal.getTime();
A couple of hints:
Use a Calendar object to work with the dates. You can set the Calendar from a Date so the way you create the dates textBoxTime and workDate are fine.
Set the values of workDate from textBoxTime using the setXXX methods on Calendar class (make workDate a Calendar)
You can use SimpleDateFormat to format as well as parse. Use this to produce the desired output.
You should be able to do this with no string parsing and just a few lines of code.
Since you already have the work date, all you need to do is convert your timebox to seconds and add it to your date object.
Use Calendar for date Arithmetic.
Calendar cal=Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.HOUR, hour);
cal.add(Calendar.MINUTE, minute);
cal.add(Calendar.SECOND, second);
Date desiredDate = cal.getTime();
You may need the following code.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class DateFormat {
public static void main(String[] args) {
try {
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Date workDate = simpleDateFormat1.parse("2011-11-27");
Calendar workCalendar= Calendar.getInstance();
workCalendar.setTime(workDate);
SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("HH:mm:ss");
Calendar time = Calendar.getInstance();
time.setTime(simpleDateFormat2.parse("06:00:00"));
workCalendar.set(Calendar.HOUR_OF_DAY, time.get(Calendar.HOUR_OF_DAY));
workCalendar.set(Calendar.MINUTE, time.get(Calendar.MINUTE));
workCalendar.set(Calendar.SECOND, time.get(Calendar.SECOND));
Date newWorkDate = workCalendar.getTime();
SimpleDateFormat simpleDateFormat3 = new SimpleDateFormat(
"yyyy-MM-dd hh:mm:ss");
System.out.println(simpleDateFormat3.format(newWorkDate));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Hope this would help you.