I have the below string which is input to my method
String xymessage="Your item(s) will be ready Today for pickup by 10:00 a.m. ";
Now how can i convert this string to a calendar object.
I was able to extract the day ie. whether its "today" or "tomorrow". And also the time ie. "10:00 a.m."
using these two parameters as input ie. today and 10:00 a.m. will it be possible for me to convert it to a calendar object?
Sample code snippet:
String xymessage="Your item(s) will be ready Today for pickup by 10:00 a.m. ";
if(null != xyMessage){
//removing empty spaces.
xyMessage=xyMessage.trim();
LOGGER.debug("sellerId:"+delivSeller.getSellerId()+" and xymessage:"+xyMessage);
if(xyMessage.contains("Today")){
//this means its today
String[] xyArray = xyMessage.split("pickup by");
if(xyArray.length == 2){
String timeVal=xyArray[1];
}
}else{
//this means its tomorrow
}
}
Use Calendar cal = Calendar.getInstance() to get a calendar object with the current date and time. Using the add(), get(), and set() methods, you can set the calendar object correctly. For instance, to change the date to tomorrow's, you could do: cal.add(Calendar.DAY_OF_MONTH, 1);
To set the hour, cal.set(Calendar.HOUR, hr); where hr was initialized with the hour to be set. Similarly for minutes, etc.
You can use SimpleDateFormat for the format you want. But as you are having a.m. or p.m. instead of plain simple AM/PM, it makes a bit of complication.
Check the below code if it helps for "today" condition :
Here variable 'time' is what you have extracted like "10:00 a.m."
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date date = new Date();
String timeArray[]=time.split(" ");
String minArray[]=timeArray[0].split(":");
date.setHours(Integer.parseInt(minArray[0]));
date.setMinutes(Integer.parseInt(minArray[1]));
if(!timeArray[1].startsWith("a")){
date.setHours(date.getHours()+12);
}
Calendar cal = Calendar.getInstance();
cal.setTime(date);
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author Administrator
*/
public class Test {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");
Calendar today = Calendar.getInstance();
Calendar tomorrow = Calendar.getInstance();
tomorrow.add(Calendar.DATE, 1);
String xyMessage = "Your item(s) will be ready Today for pickup by 10:00 a.m. ";
if (null != xyMessage) {
//removing empty spaces.
xyMessage = xyMessage.trim();
if (xyMessage.contains("Today")) {
//this means its today
String[] xyArray = xyMessage.split("pickup by ");
String time = xyArray[1].replace(".", "");
today.set(Calendar.HOUR_OF_DAY, sdf.parse(time).getHours());
System.out.println("calendar:" + finalFormat.format(today.getTime()));
} else {
//this means its tomorrow
String[] xyArray = xyMessage.split("pickup by ");
String time = xyArray[1].replace(".", "");
tomorrow.set(Calendar.HOUR_OF_DAY, sdf.parse(time).getHours());
System.out.println("calendar:" + finalFormat.format(tomorrow.getTime()));
}
}
}
}
just use SimpleDateFormat("hh:mm aa")
Try below code.
String val = "10:00 a.m";
val = val.replace(".", "");
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a");
Calendar temp = Calendar.getInstance();
temp.setTime(dateFormat.parse(val));
Calendar cal = Calendar.getInstance();
if ("tomorrow".equalsIgnoreCase("YOUR_STRING")) {
cal.add(Calendar.DAY_OF_YEAR, 1);
}
cal.set(Calendar.HOUR_OF_DAY, temp.get(Calendar.HOUR_OF_DAY));
cal.set(Calendar.MINUTE, temp.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.DAY_OF_MONTH) + ":"
+ (cal.get(Calendar.MONTH) + 1) + ":"
+ cal.get(Calendar.HOUR_OF_DAY) + ":"
+ cal.get(Calendar.MINUTE));
}
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 try to subtract one day when the time inside 0:00 am - 12:00 am.
ex: 2012-12-14 06:35 am => 2012-12-13
I have done a function and It's work. But my question is any other better code in this case? Much simpler and easy to understand.
public String getBatchDate() {
SimpleDateFormat timeFormatter = new SimpleDateFormat("H");
int currentTime = Integer.parseInt(timeFormatter.format(new Date()));
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyyMMdd");
String Date = dateFormatter.format(new Date());
if ( 0 <= currentTime && currentTime <= 12){
try {
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(dateFormatter.parse(Date));
shiftDay.add(Calendar.DATE, -1);
Date = dateFormatter.format(shiftDay.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d("BatchDate:", Date);
}
return Date;
}
THANKS,
Calendar shiftDay = Calendar.getInstance();
shiftDay.setTime(new Date())
if(shiftDay.get(Calendar.HOUR_OF_DAY) <= 12){
shiftDay.add(Calendar.DATE, -1);
}
//your date format
Use the Calendar class to inspect and modify the Date.
Calendar cal = new GregorianCalendar(); // initializes calendar with current time
cal.setTime(date); // initializes the calender with the specified Date
Use cal.get(Calendar.HOUR_OF_DAY) to find out the hour within the day.
Use cal.add(Calendar.DATE, -1) to set the date one day back.
Use cal.getTime() to get a new Date instance of the time that was stored in the calendar.
As with nearly all questions with regard to Date / Time, try Joda Time
public String getBatchDate() {
DateTime current = DateTime.now();
if (current.getHourOfDay() <= 12)
current = current.minusDays(1);
String date = current.toString(ISODateTimeFormat.date());
Log.d("BatchDate:" + date);
return date;
}
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.
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();
I am using GregorianCalander and when i tried to get todays date using the following code i am getting a date which is backdated to one month. The code i have used is as follows.
Calendar gcal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
today = getTime(gcal);
//date = dateFormat.format(calendar.getTime());
System.out.println("Today: " + today);
Please help me to solve this issue.
The output is :
Today: Thu Apr 28 00:00:00 NZST 2011
EDIT
private Date getTime(Calendar gcal) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
String day = form_helper.round(gcal.get(GregorianCalendar.DAY_OF_MONTH));
String month = form_helper.round(gcal.get(GregorianCalendar.MONTH));
String year = form_helper.round(gcal.get(GregorianCalendar.YEAR));
String date = day + "/" + month + "/" + year;
System.out.println(sdf.parse(date));
return sdf.parse(date);
} catch (ParseException ex) {
Logger.getLogger(timesheet_utility.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
I think internal numbering of months starts with 0, not 1. So, you probably need to somewhere add +1.
Edit: after you showed some more code: The needed change is
String month = form_helper.round(gcal.get(GregorianCalendar.MONTH) + 1);
What does the getTime() method do? Remember that in Java, the constants for the month begin at 0 and not at 1, so Calendar.JANUARY == 0.
EDIT
Since you posted the code for getTime() I think this is the problem:
gcal.get(GregorianCalendar.MONTH) returns the month value that Java internally stores, that is, a 0-indexed month value so a value for "May" would actually be the integer "4".
When the value "4" is put back into the date parser, "April" results, since the parser interprets dates as a human would. So you simply have to add 1 to this value to ensure the parsing happens properly.
If you want a Date object that represents 12:00AM (or 00:00) for today, why not just do:
private Date getTime() {
Calendar gcal = new GregorianCalendar();
gcal.set(Calendar.HOUR_OF_DAY, 0);
gcal.set(Calendar.MINUTE, 0);
gcal.set(Calendar.SECOND, 0);
gcal.set(Calender.MILLISECOND, 0);
return gcal.getTime();
}
Here's my attempt:
package forums;
import java.util.Date;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Deepak
{
public static void main(String[] args) {
try {
(new Deepak()).run();
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
Calendar calendar = new GregorianCalendar();
Date today = calendar.getTime();
System.out.println("Today: " + today);
}
}
and the output is the expected:
Today: Sat May 28 22:00:52 EST 2011