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.
Related
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
This question already has answers here:
Why do I get the "Unhandled exception type IOException"?
(6 answers)
java get week of year for given a date
(4 answers)
Closed 7 years ago.
I want to get the current week with a given date, e.g if the date is 2016/01/19, the result will be : week number: 3
I've seen some questions and answers about this but I'm not able to achieve what I want. Here is what I've done :
public static int getCurrentWeek() {
String input = "20160115";
String format = "yyyyMMdd";
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
return week;
}
I've took this code from this question but I have an error on this line :
Date date = df.parse(input);
unhandled exception type ParseException
Use Java 8 LocalDate and WeekFields:
private int getCurrentWeek() {
LocalDate date = LocalDate.now();
WeekFields weekFields = WeekFields.of(Locale.getDefault());
return date.get(weekFields.weekOfWeekBasedYear());
}
Look at this changed code:
String input = "20160115";
String format = "yyyyMMdd";
try {
SimpleDateFormat df = new SimpleDateFormat(format);
Date date = df.parse(input);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int week = cal.get(Calendar.WEEK_OF_YEAR);
System.out.println("Input " + input + " is in week " + week);
return week;
} catch (ParseException e) {
System.out.println("Could not find a week in " + input);
return 0;
}
You need to catch ParseException and deal with it somehow. This could mean returning a "default" number (0 in this case) or passing the exception along (by declaring a throws on your method)
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
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;
I know about to get the date in android with the help of the calender instance.
Calendar c = Calendar.getInstance();
System.out.println("====================Date is:"+ c.get(Calendar.DATE));
But with that i got only the number of the Date. . .
In My Application i have to do Some Calculation based on the Date Formate. Thus if the months get changed then that calculation will be getting wrong.
So for that reason i want the full date that gives the Month, Year and the date of the current date.
And what should be done if i want to do Some Calculation based on that date ?
As like: if the date is less then two weeks then the message should be printed. . .
Please Guide me in this.
Thanks.
Look at here,
Date cal=Calendar.getInstance().getTime();
String date = SimpleDateFormat.getDateInstance().format(cal);
for full date format look SimpleDateFormat
and IF you want to do calculation on date instance I think you should use, Calendar.getTimeInMillis() field on these milliseconds make calculation.
EDIT: these are the formats by SImpleDateFormat class.
String[] formats = new String[] {
"yyyy-MM-dd",
"yyyy-MM-dd HH:mm",
"yyyy-MM-dd HH:mmZ",
"yyyy-MM-dd HH:mm:ss.SSSZ",
"yyyy-MM-dd'T'HH:mm:ss.SSSZ",
};
for (String format : formats) {
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
}
EDIT: two date difference (Edited on Date:09/21/2011)
String startTime = "2011-09-19 15:00:23"; // this is your date to compare with current date
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date1 = dateFormat.parse(startTime);
// here I make the changes.... now Date d use a calendar's date
Date d = Calendar.getInstance().getTime(); // here you can use calendar beco'z date is now deprecated ..
String systemTime =(String) DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime());
SimpleDateFormat df1;
long diff = (d.getTime() - date1.getTime()) / (1000);
int Totalmin =(int) diff / 60;
int hours= Totalmin/60;
int day= hours/24;
int min = Totalmin % 60;
int second =(int) diff % 60;
if(day < 14)
{
// your stuff here ...
Log.e("The day is within two weeks");
}
else
{
Log.e("The day is more then two weeks");
}
Thanks.
Use SimpleDateFormat class,
String date = SimpleDateFormat.getDateInstance().format(new Date());
you can use
//try different flags for the last parameter
DateUtils.formatDateTime(context,System.currentTimeMillis(),DateUtils.FORMAT_SHOW_DATE);
for all options check http://developer.android.com/reference/android/text/format/DateUtils.html
try this,
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
int day = c.get(Calendar.DAY_OF_MONTH);
System.out.println("Current date : "
+ day + "/" + (month + 1) + "/" + year);
}
I'm using following methods to get date and time. You can change the locale here to arabic or wot ever u wish to get date in specific language.
public static String getDate(){
String strDate;
Locale locale = Locale.US;
Date date = new Date();
strDate = DateFormat.getDateInstance(DateFormat.DEFAULT, locale).format(date);
return strDate;
}
public static String getTime(){
String strTime;
Locale locale = Locale.US;
Date date = new Date();
strTime = DateFormat.getTimeInstance(DateFormat.DEFAULT, locale).format(date);
return strTime;
}
you can get the value and save it on String as below
String Date= getDate();
String Time = getTime();