simpledateformat for month and day in month only [duplicate] - java

This question already has answers here:
Calendar date to yyyy-MM-dd format in java
(11 answers)
Closed 8 years ago.
I require this format MonthDay, example 0422
I'm creating
SimpleDateFormat sdf = new SimpleDateFormat("MMdd");
and giving it the current month and current day
curDate = sdf.parse(curMon+""+curDay);
but I'm getting this format:
Thu Jun 07 00:00:00 CEST 1973
What do I need to do?

Instead of using parse, use format as follows:
SimpleDateFormat s = new SimpleDateFormat("MMdd");
String d = s.format(new Date());
System.out.println(d);
This will generate, since today is 27th May:
0527

I hope below code will help you...
strDate="2014-08-19 15:49:43";
public String getMonth(String strMonth) {
int month = Integer.parseInt(strMonth.substring(0, 2));
int day = Integer.parseInt(strMonth.substring(strMonth.length() - 2,
strMonth.length()));
String d = (new DateFormatSymbols().getMonths()[month - 1]).substring(
0, 3) + " " + day;
return d;
}
public static String smallDate(String strDate) {
String str = "";
try {
SimpleDateFormat fmInput = new SimpleDateFormat("yyyy-MM-dd");
Date date = fmInput.parse(strDate);
SimpleDateFormat fmtOutput = new SimpleDateFormat("MMdd");
str = fmtOutput.format(date);
str = getMonth(str);
Log.d("Output date: "+str);
return str;
} catch (Exception e) {
}
}

use like that
Date date; // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String month = cal.get(Calendar.MONTH).toString();
String day = cal.get(Calendar.DAY_OF_MONTH).toString();
String mmdd=month+""+day;

Related

How to get a required Date format using SimpleDateFormat [duplicate]

This question already has answers here:
Java date format conversion - getting wrong month
(8 answers)
How to parse a date? [duplicate]
(5 answers)
Closed 5 years ago.
My method is :
public String changeCurrentDate(Integer variant){
String currentTime = TestApp.getInstance().getDriver().findElement(By.id("common.HeaderComponent.mainLayout.serverTimeLabel")).getText();
String currentDate = currentTime.substring(0, 10);
System.out.println("currentDate " +currentDate);
String date = null;
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
try{
Date date3 = df.parse(currentDate);
df.format(date3);
System.out.println("date3 " +date3);
Date previousDate = DateUtils.addDays(date3, variant);
date = previousDate.toString();
return date;
}catch (Exception e){
}
return date;
}
Note : currentTime variable always have the value like "18/12/2017"
I'm expecting result of date in dd/mm/yyyy format. but it always gives "Wed Jan 18 00:12:00 IST 2017" like this.
Run Time Results :
currentDate 18/12/2017
date3 Wed Jan 18 00:12:00 IST 2017
You should return the formatted date, not the toString() of the date. Try this:
Date previousDate = DateUtils.addDays(date3, variant);
return df.format(previousDate);
df.format simply returns a String representation of the Date with the format applied, therefore the line you have in your code has no effect.
Try changing you code to use the formatted output instead:
public String changeCurrentDate(Integer variant){
String currentTime = TestApp.getInstance().getDriver().findElement(By.id("common.HeaderComponent.mainLayout.serverTimeLabel")).getText();
String currentDate = currentTime.substring(0, 10);
System.out.println("currentDate " +currentDate);
DateFormat df = new SimpleDateFormat("dd/mm/yyyy");
Date date3 = df.parse(currentDate);
System.out.println("date3 " + df.format(date3));
Date previousDate = DateUtils.addDays(date3, variant);
return previousDate.toString();
}
Also - its bad to catch Exception, so you should remove that.
We should always try to find out the more convenient way so that we can further use it. In that case, we can use below method:
public String dateString(String input) {
SimpleDateFormat parser = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");
String formattedDate = "";
try {
Date date = parser.parse(input);
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
formattedDate = formatter.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return formattedDate;
}
You can easily call this method like below:
Date date3 = df.parse(currentDate);
df.format(date3);
String input = date3.toString();
String requiredDate = dateString(input);
System.out.println("requiredDate: "+ requiredDate);
Which returns the output like below:
requiredDate: 18/12/2017

Remove the hour,minute and seconds from date gotten from server as JSON

I am getting some JSON data from server that includes dates too. But it shows the date like this 2017-07-20 00:00:00 but I want to just see the date like this:2017-07-20, and i checked the previous questions about this issue but all of them were based on the date in the android side. And the problem is that I get the date as JSON and because of that I don't know how to remove Time from it.
Did you try to simple parse this string like this?
String date_string = "2017-07-20 00:00:00";
String[] parsed = date_string.split(" ");
String your_wanted_string = parsed[0];
System.out.println(your_wanted_string);
EDIT
You have to convert string into Date like here : https://stackoverflow.com/a/4216767/1979882
Convert Date to milliseconds. Or use Calendar class.
Calculate the difference between the values.
An example:
http://www.mkyong.com/java/how-do-get-time-in-milliseconds-in-java/
public class TimeMilisecond {
public static void main(String[] argv) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "22-01-2015 10:20:56";
Date date = sdf.parse(dateInString);
System.out.println(dateInString);
System.out.println("Date - Time in milliseconds : " + date.getTime());
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
System.out.println("Calender - Time in milliseconds : " + calendar.getTimeInMillis());
}
}
String date_from_json="your date goes here";
parseDate(date_from_json);
public String parseDate(String s) {
SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
SimpleDateFormat outputFormat = new SimpleDateFormat("yyyy-mm-dd");
Date date = null;
String str = null;
try {
date = inputFormat.parse(s);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
You can use my javascript function to do this task from client side:
function formatDate(dateString) {
var date = new Date("2017-07-20 00:00:00"),
dd = date.getDate(),
mm = date.getMonth() + 1,
yyyy = date.getFullYear();
mm = mm < 10 ? '0' + mm : mm;
return dd + '-' + mm +'-' + yyyy;
}
call:
var dateStr = formatDate("2017-07-20 00:00:00");
demo

How to get month and day from given string? [duplicate]

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

Returning a time in String [duplicate]

This question already has answers here:
Current Date & Time in Java
(5 answers)
Closed 9 years ago.
I'm trying to write a method to return a Time in util.Date to a string. I am getting '0' when i am trying to return whether the time is in AM or PM and the minutes are not displaying the 0 in front. I am trying to return the time in the format of HH:mm am_pm
Here is my method:
public String getTime() {
Calendar cal = Calendar.getInstance();
int hr = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
return String.valueOf(hr) + ":" + String.valueOf(min) + " " + cal.get(Calendar.AM_PM);
}
Input: 2:00 (HH:mm SimpleDateFormat in a JFormattedTextField)
Output: 2:0 0
EDIT: tried using the SimpleDateFormat but i am getting a type mistmatch error
public String getTime()
{
SimpleDateFormat format = new SimpleDateFormat("HH:mm aa");
date = format.toString().toString();
return date;
}
Something like this will do:
DateFormat df = new SimpleDateFormat("hh:mm aa");
String timeNow = df.format(new Date());
Use SimpleDateFormat instead.
public String getTime() {
// If you want the current hour
SimpleDateFormat format = new SimpleDateFormat("HH:mm aa");
return format.format(new Date());
}
cal.get(Calendar.AM_PM) returns 0 for AM and 1 for PM. Replace the last line with:
return String.valueOf(hr) + ":" + String.valueOf(min) + " " + cal.get(Calendar.AM_PM) == Calendar.AM ? "am" : "pm";
Consider using SimpleDateFormat.

How to convert newyork timezone to Asia time zone [duplicate]

This question already has answers here:
SimpleDateFormat ignoring month when parsing
(4 answers)
Closed 2 years ago.
How to convert newyork timezone time to "Asia/Kolkata" date and time?
my Input String:
11/28/2012 8:59am
My code:
String dtStart = "11/28/2012 8:59am";
SimpleDateFormat format = new SimpleDateFormat("mm/dd/yyyy hh:mma");
format.setTimeZone(TimeZone.getTimeZone("America/New_York"));
try {
Date date = format.parse(dtStart);
Log.i("clock", date.toString());
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(date.getTime());
cal.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));
int chour = cal.get(Calendar.HOUR_OF_DAY);
int cminute = cal.get(Calendar.MINUTE);
int dd = cal.get(Calendar.DAY_OF_MONTH);
int mm =cal.get(Calendar.MONTH);
int yy =cal.get(Calendar.YEAR);
String mode="AM";
if(chour>12)
{
chour=chour-12;
mode="PM";
}
String mytime=Integer.toString(chour)+":"+Integer.toString(cminute)+" "+mode;
String mydate=Integer.toString(dd)+"/"+Integer.toString(mm)+"/"+Integer.toString(yy);
Log.i("clock", mytime);
Log.i("clock", mydate);
} catch (ParseException e) {
e.printStackTrace();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
My output Log:
Sat Jan 28 19:29:00 GMT+05:30 2012
7:29 PM
28/0/2012
Here my time is correct,but date is wrong. I expect 28/11/2012.I am not able trace where i did wrong?
the issue is in format you entered: "mm/dd/yyyy hh:mma". I believe you wanted to do this: "MM/dd/yyyy hh:mma"
SimpleDateFormat formatter = new SimpleDateFormat("MM/DD/YYYY hh:mm:ss a");
String dtStart = "11/28/2012 08:59 am";
Date dateObj = formatter.parse(dtStart);
cal.setTime(dateObj);
fromTZObj = TimeZone.getTimeZone("America/New_York");
toTZObj = TimeZone.getTimeZone("Asia/Kolkata");
Calendar fromCal = new GregorianCalendar(fromTZObj);
fromCal.set(cal.get(1), cal.get(2), cal.get(5), cal.get(11), cal.get(12),
cal.get(13));
Calendar toCal = new GregorianCalendar(toTZObj);
toCal.setTimeInMillis(fromCal.getTimeInMillis());
Date dd = toCal.getTime();
formatter.setTimeZone(toTZObj);
String formattedDate = format.format(dd);
System.out.println(formattedDate);

Categories