Is it possible that i can get todays date , rather than time ??
This is my code
public static void main(String args[]) throws ParseException{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
}
Why is todays date is shown as before date ??
public class Ravi {
public static void main(String args[]) throws ParseException {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
System.out.println("Todays Date"+dateFormat.format(date));
List currentObject = new ArrayList();
currentObject.add("2012-09-27");
Date ExpDate = dateFormat.parse((String) currentObject.get(0));
System.out.println("ddd"+ExpDate);
if (ExpDate.before(date)) {
System.out.println("true");
}
else {
System.out.println("false");
}
}
}
System.out.println(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
It will print 2012-09-27
Because Date is always the full current time e.g. 2012.09.27 12:45:23
Whilst your new Formated date is 2012.09.27 00:00:00 therefor the output is correct.
If you want to get false you will need to set hours, minutes and seconds to 0.
Using Calendar:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Calendar cal = Calendar.getInstance();
System.out.println(dateFormat.format(cal.getTime()));
Using Date:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date();
System.out.println(dateFormat.format(date));
Comparing Dates with Calendar:
Calendar old = Calendar.getInstance();
old.set(Calendar.YEAR, 2011);
Calendar now = Calendar.getInstance();
old.before(now));
Note you may want to set Hours Minutes and Seconds to 0.
Getting today date in yyyy-MM-dd format.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String output = sdf.format(new Date());
System.out.println(output);
Why is todays date is shown as before date ??
when you do dateFormat.parse("2012-09-27");
date what you will get it will be 00h00min00sec 2012-09-27
so when you compare it with new Date(); you will get today date but couple hours(and minutes, and seconds) later, and that is why "2012-09-27" is before new Date()
You can do something like this:
Date date=new Date();
SimpleDateFormat sd=new SimpleDateFormat("yyyyMMdd HHmmss");
String strDate=sd.format(date);
String dateNow=strDate.substring(0,strDate.indexOf(" "));
String timeNow=strDate.substring(strDate.indexOf(" ")+1);
Hope this helps.
public static void main(String args[]) throws ParseException{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
sysout(dateFormat.format(today))
}
Related
I have a weird problem I used Java to get a current date but I am getting different results on several devices, on one correct & on another wrong.
Here is my code:
public String getCurrentDate() {
/// get date
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH);
dateFormat.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
Date date = new Date();
System.out.println(dateFormat.format(date)); //2017-11-13 18:20:46 correct time is 11am
return dateFormat.format(date);
}
On the device that gives the wrong result I set automatic time zone use network-provided time zone & time of the device is correct.
Are testing with real devices?
You can also try the Calendar Class that are from Android. for more info visit (https://developer.android.com/reference/java/util/Calendar.html)
Check the Example bellow:
Calendar current_time_cal = Calendar.getInstance();
current_time_cal.setTimeZone(TimeZone.getTimeZone("Asia/Tehran"));
int hours = current_time.get(Calendar.HOUR);
int current_am_pm = current_time.get(Calendar.AM_PM);
current_time_cal.set(Calendar.HOUR_OF_DAY, (hours == 0)? 12 : hours);
current_time_cal.set(Calendar.MINUTE, current_time.get(Calendar.MINUTE));
current_time_cal.set(Calendar.SECOND, 0);
Try this:
Calendar c = Calendar.getInstance();
System.out.println("Current time: " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy");
String formattedDate = df.format(c.getTime());
You can use this method to get current time from your device:
public String getCurrentDate() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar calendar = Calendar.getInstance();
String date = sdf.format(calendar.getTime());
return date;
}
This method will return current date as string.
I am working on Java. I have a String and I want to convert it into Date Format. Please see the lines of code for more details.
String dateString = "4:16:06 PM";
I want to convert it into the below Date:
Date convertedDate = 2014-04-22 16:16:06.00
How can I do this?
try this:
// get current date
SimpleDateFormat dateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
String a = dateFormat1.format(new Date());
// add current date to your time string
String dateString = a + " 4:16:06 PM";
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd h:mm:ss a");
try {
// parse it. This is you date object.
Date d = dateFormat2.parse(dateString);
} catch (ParseException ex) {
ex.printStackTrace();
}
I think you are looking for following:
DateFormat df1 = new SimpleDateFormat("h:mm:ss a");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
String dateString = "4:16:06 PM";
Date date;
try {
Calendar cal = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
date = df1.parse(dateString);
cal.setTime(date);
// Reset year, month, day to current state
cal.set(Calendar.YEAR, cal2.get(Calendar.YEAR));
cal.set(Calendar.MONTH, cal2.get(Calendar.MONTH));
cal.set(Calendar.DAY_OF_MONTH, cal2.get(Calendar.DAY_OF_MONTH));
Date convertedDate = cal.getTime();
System.out.println(df2.format(convertedDate));
} catch (ParseException e) {
e.printStackTrace();
}
Try this ,
String str_date="13-09-2011";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date);
System.out.println("Date " +date.getTime());
Try this
public class DateClass
{
public static void main(String[] args) throws Exception {
String target = "4:16:06 PM";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat dff = new SimpleDateFormat("HH:mm:ss");
Date d=new Date();
String abc="4:16:06 PM";
Date result = new SimpleDateFormat("h:mm:ss a").parse(abc);
System.out.println("The result is "+df.format(d)+" "+dff.format(result));
}
}
Feel free to ask anything if you don't understand it and plz respond did it work or not?
Here is my code.
public String getDateTime()
{
String dateAndTime =
(new SimpleDateFormat("hh:mm aaa")).format(new Date());
return dateAndTime;
}
public String getDate()
{
android.text.format.DateFormat df = new android.text.format.DateFormat();
String Date = df.format("MM-dd-yyyy", new java.util.Date()).toString();
return Date;
}
I have searched about this. but, i cant find the perfect answer. Please help me.
You can use the below function
private Date shiftTimeZone(Date date, TimeZone sourceTimeZone, TimeZone targetTimeZone) {
Calendar sourceCalendar = Calendar.getInstance();
sourceCalendar.setTime(date);
sourceCalendar.setTimeZone(sourceTimeZone);
Calendar targetCalendar = Calendar.getInstance();
for (int field : new int[] {Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND}) {
targetCalendar.set(field, sourceCalendar.get(field));
}
targetCalendar.setTimeZone(targetTimeZone);
System.out.println("........"+targetCalendar.getTimeZone());
return targetCalendar.getTime();
}
Usage:
Date date= new Date();
SimpleDateFormat sf = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
sf.format(date);
TimeZone tz = TimeZone.getTimeZone("GMT") OR TimeZone tz = sf.getTimeZone();
TimeZone tz1 = TimeZone.getTimeZone("EST");
Date c= shiftTimeZone( date,tz,tz1);
System.out.println("Format : " + sf.format(c));
Output
sun.util.calendar.ZoneInfo[id="EST",offset=-18000000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]
Format : 01-05-2013 16:23:57
You can find your answer here :
Date and time conversion to some other Timezone in java
You have to use TimeZone class and Calendar class.
Get current time :
Calendar currentdatetime = Calendar.getInstance();
Just pass your time zone name in TimeZone class like this :
TimeZone.getTimeZone("EST");
Use DateFormater
DateFormat formatter = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
Then format your time like this :
formatter.setTimeZone(obj);
and get output like this :
System.out.println("EST Time is : "+ formatter.format(currentdatetime .getTime())
This question already has answers here:
How to check if a date Object equals yesterday?
(9 answers)
Closed 8 years ago.
The following function produces today's date; how can I make it produce only yesterday's date?
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
return dateFormat.format(date).toString();
}
This is the output:
2012-07-10
I only need yesterday's date like below. Is it possible to do this in my function?
2012-07-09
Update
There has been recent improvements in datetime API with JSR-310.
Instant now = Instant.now();
Instant yesterday = now.minus(1, ChronoUnit.DAYS);
System.out.println(now);
System.out.println(yesterday);
https://ideone.com/91M1eU
Outdated answer
You are subtracting the wrong number:
Use Calendar instead:
private Date yesterday() {
final Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return cal.getTime();
}
Then, modify your method to the following:
private String getYesterdayDateString() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
return dateFormat.format(yesterday());
}
See
IDEOne Demo
You can do following:
private Date getMeYesterday(){
return new Date(System.currentTimeMillis()-24*60*60*1000);
}
Note: if you want further backward date multiply number of day with 24*60*60*1000 for example:
private Date getPreviousWeekDate(){
return new Date(System.currentTimeMillis()-7*24*60*60*1000);
}
Similarly, you can get future date by adding the value to System.currentTimeMillis(), for example:
private Date getMeTomorrow(){
return new Date(System.currentTimeMillis()+24*60*60*1000);
}
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Use Calender Api
Try this one:
private String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Create a calendar object with today date. Calendar is in java.util pakage.
Calendar calendar = Calendar.getInstance();
// Move calendar to yesterday
calendar.add(Calendar.DATE, -1);
// Get current date of calendar which point to the yesterday now
Date yesterday = calendar.getTime();
return dateFormat.format(yesterday).toString();
}
Try this;
public String toDate() {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
return dateFormat.format(cal.getTime());
}
changed from your code :
private String toDate(long timestamp) {
Date date = new Date (timestamp * 1000 - 24 * 60 * 60 * 1000);
return new SimpleDateFormat("yyyy-MM-dd").format(date).toString();
}
but you do better using calendar.
There is no direct function to get yesterday's date.
To get yesterday's date, you need to use Calendar by subtracting -1.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Have a string like 2011-03-09T03:02:10.823Z, how to convert it to Date or calendar object in Java?
You can use SimpleDateFormat#parse() to convert a String in a date format pattern to a Date.
String string = "2011-03-09T03:02:10.823Z";
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
Date date = new SimpleDateFormat(pattern).parse(string);
System.out.println(date); // Wed Mar 09 03:02:10 BOT 2011
For an overview of all pattern characters, read the introductory text of SimpleDateFormat javadoc.
To convert it further to Calendar, just use Calendar#setTime().
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
// ...
I want to show "2017-01-11" to "Jan 11" and this is my solution.
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat df_output = new SimpleDateFormat("MMM DD");
Calendar cal=Calendar.getInstance();
Date date = null;
try {
date = df.parse(selectedDate);
String outputDate = df.format(date);
date = df_output.parse(outputDate);
cal.setTime(date);
} catch (ParseException e) {
e.printStackTrace();
}
import java.util.*;
import java.text.*;
public class StringToCalender {
public static void main(String[] args) {
try { String str_date="11-June-07";
DateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = (Date)formatter.parse(str_date);
Calendar cal=Calendar.getInstance();
cal.setTime(date);
System.out.println("Today is " +date );
} catch (ParseException e)
{System.out.println("Exception :"+e); }
}
}
Your given date is taken as a string that is converted into a date type by using the parse() method. The parse() method invokes an object of DateFormat. The setTime(Date date) sets the formatted date into Calendar. This method invokes to Calendar object with the Date object.refer
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Date date = sdf.parse(strDate);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
try this.(strDate id your string format of Date)