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();
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 using AngularJS to get date and time separately as user input through via HTML. But timestamp is a single column in my database.
Date and Time field are coming as two different timestamps in my Java server.
Date --> 2015-11-11 00:00:00.0
Time --> 1970-01-01 23:11:00.0
I want to combine date part from Date and time part from Time and insert as timestamp into my database
DateTime --> 2015-11-11 23:11:00.0
Assuming you're able to create these as java.util.Date objects, you can rely on their milleseconds-from-epoch to get this information:
long dateMills = date.getTime();
long timeMills = time.getTime();
long dateTimeMills = dateMills + timeMills();
long dateTime = new Date(dateTimeMills);
Alternatively, you could set the fields individually.
GregorianCalendar dateCal = new GregorianCalendar();
GregorianCalendar timeCal = new GregorianCalendar();
dateCal.setTime(date.getTime());
timeCal.setTime(time.getTime());
int year = dateCal.get(Calendar.YEAR);
int month = dateCal.get(Calendar.MONTH);
int day = dateCal.get(Calendar.DAY_OF_MONTH);
int hour = timeCal.get(Calendar.HOUR_OF_DAY);
int minute = timeCal.get(Calendar.MINUTE);
int second = timeCal.get(Calendar.SECOND);
GregorianCalendar dateTimeCal = new GregorianCaledar(year, month, day, hour, minute, second);
Date dateTime = dateTimeCal.getTime();
No need to use the date and time as String, just use Calendar and get the fields separately:
public static Date combineDateTime(Date date, Date time) {
Calendar dateCalendar = Calendar.getInstance();
dateCalendar.setTime(date);
Calendar timeCalendar = Calendar.getInstance();
timeCalendar.setTime(time);
dateCalendar.set(Calendar.HOUR, timeCalendar.get(Calendar.HOUR));
dateCalendar.set(Calendar.MINUTE, timeCalendar.get(Calendar.MINUTE));
dateCalendar.set(Calendar.SECOND, timeCalendar.get(Calendar.SECOND));
return dateCalendar.getTime();
}
You can simply use String.split and create your required String date and use it as required.
SimpleDateFormat formatter = new SimpleDateFormat("hh:mm a");
SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateInString = "12:30 AM";
String dateInString2 = "2017-10-16 10:00:00";
try {
Date date1 = formatter.parse(dateInString);
Date date2 = formatter2.parse(dateInString2);
String[] d1 = formatter2.format(date1).split(" ");
String[] d2 = formatter2.format(date2).split(" ");
String neededDate = d2[0] + " " + d1[1];
System.out.println(date1);
System.out.println(formatter2.format(date1));
System.out.println(formatter2.format(date2));
System.out.println(neededDate);
} catch (ParseException e) {
e.printStackTrace();
}
Output
Thu Jan 01 00:30:00 IST 1970
1970-01-01 00:30:00
2017-10-16 10:00:00
2017-10-16 00:30:00
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();
I have created a web service which returns the date of an event which is initially captured by the getDate() function. I want the date returned by this function (something along this format : 2013-05-17 14:52:00.943) to be parsed and shown to the user in the DD-MM-YYYY format.
Any suggestions? I haven't found any solution along this direction yet.
I have tried this code and it's work fine for me,Please Try my code below: Please upvote to Tarun also coz he gave almost right answer.just he did mistake that he passes cal.getTime() method instead of pDate
String formatDate = p.format(pDate);
and second mistake in format like"DD-MM-YYYY" but actual format is:
"dd-MM-yyyy" not "DD-MM-YYYY"
I have done changes in it and modify it.
String dateStr = "2013-05-16 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S"); // your web service format
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy"); // your required format
String formatDate = p.format(pDate); // convert it in your required format
SimpleDateFormat formatter = new SimpleDateFormat("EEEE"); // Day format as you want EEE for like "Sat" and EEEE for like "Saturday"
String Day = formatter.format(pDate); // This will give you a day as your selected format
System.out.println("Date & Day>>>"+formatDate+" "+Day);
// For GMT format your format should be like this: "2013-05-16 14:52:00.943 GMT+05:30"
// Give it to me in GMT time.
c.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println("GMT time: " + c.format(pDate));
Output:
Date & Day>>>16-05-2013 Thursday
GMT time: 2013-05-16 02:52:00.943 Greenwich Mean Time
Joda time:
you can download 2.0 jar file of joda time from here:
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter
.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date2 = jodaParsed.toDate();
System.out.println("Date & Day:" + jodaParsed.getDayOfMonth() + "-" + jodaParsed.getMonthOfYear() + "-" + jodaParsed.getYear() + " " + jodaParsed.getHourOfDay() + ":" + jodaParsed.getMinuteOfHour()+" "+jodaParsed.dayOfWeek().getAsText());
output:
Date & Day:17-5-2013 16:27 Friday
Hope it will work for you.
String dateStr = "2013-05-17 14:52:00.943";
SimpleDateFormat c = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.S");
Date pDate = c.parse(dateStr);
SimpleDateFormat p = new SimpleDateFormat("dd-MM-yyyy");
String formatDate = p.format(pDate);
You can use Joda Time if you have colon in time offset.
DateTimeFormatter jodaFormatter = ISODateTimeFormat.dateTime();
DateTime jodaParsed = jodaFormatter.parseDateTime("2013-05-17T16:27:34.9+05:30");
Date date = jodaParsed.toDate();
Calendar c = Calendar.getInstance();
c.setTime(date);
c.get(Calendar.DATE));
More info about joda can be found here.
Use a SimpleDateFormat to parse the date and then print it out with a SimpleDateFormat withe the desired format.
Example:
SimpleDateFormat format1 = new SimpleDateFormat("MM/dd/yyyy");
SimpleDateFormat format2 = new SimpleDateFormat("dd-MM-yyyy");
Date date = format1.parse("05/18/2013");
System.out.println(format2.format(date));
Output:
11-05-2013
Edit:
Calendar cal = Calendar.getInstance();
cal.setTime(specific_date);
int dayOfMonth = cal.get(Calendar.DAY_OF_WEEK);
String dayOfMonthStr = String.valueOf(dayOfMonth);
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())