I am trying to get long value of a string.
final long date = System.currentTimeMillis();
Date dt = new Date(date);
SimpleDateFormat sdf = new SimpleDateFormat(" HH:mm aa");
String time1 = sdf.format(dt);
try {
dt = sdf.parse(time1);
} catch (ParseException e)
{
e.printStackTrace();
}
long millis = dt.getTime();
Log.d("Current time", millis + "");
Here I get negative value of millis(current time).
Please help me out of this.
public static long getLongDate(String d) {
long dateInLong = 0;
try {
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = formatter.parse(d);
dateInLong = date.getTime();
} catch (Exception e) {
Log.d(Constants.TAG, "" + e.getMessage());
}
return dateInLong;
}
try this.
i have try, but the output didn't a negative value. after the back and forth conversion, you have drop out the year, month and day value. so the dt you get back from parse method has been set to 1970-01-04.
Related
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format("2017-01-04"));
The above is my code and when I try to convert the date to gmt I get the error:
Exception in thread "main" java.lang.IllegalArgumentException: Cannot
format given Object as a Date at
java.text.DateFormat.format(DateFormat.java:310) at
java.text.Format.format(Format.java:157) at
Sample.main(Sample.java:24)
Please point out what am I doing wrong.
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.format(new Date()));
This above code is working fine but I need something that works for any date.
And when I try this code:
try {
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'SSSX");
df.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("Current date and time in GMT: " + df.parse("2017-01-04"));
} catch(Exception e) {
e.printStackTrace();
}
I am getting Unparseable date: "2017-01-04". Please tell me how to fix it
Try it..
String s = "2016-11-21 13:30:0.0";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss);
Date d = null;
try
{
d = format.parse(s);
} catch (ParseException e)
{
e.printStackTrace();
}
SimpleDateFormat gmtFormat = new SimpleDateFormat("yyyy-MM-dd'T'SSSX");
gmtFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println(gmtFormat.format(d));
When you have a date object then you can format it as you want:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
format.setTimeZone(TimeZone.getTimeZone("GMT"));
//create a calendar representing your date.
Calendar cal = Calendar.getInstance();
cal.set(2017, 01, 04);
//format the date object to the pattern you want.
String DateToStr = format.format(cal.getTime());
System.out.println(DateToStr);
If you have your date as string you can also do:
String string = "2017-01-04";
DateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
format1.setTimeZone(TimeZone.getTimeZone("GMT"));
Date date = null;
try {
date = format1.parse(string);
} catch (Exception ex) {
ex.printStackTrace();
}
System.out.println(date);
The below code is to help in understanding better - you can try uncommenting the commented lines and compare the results. The point of interest for you in this whole block is gdf.parse(gmtFormat)
Date date = new Date();
DateFormat idf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
idf.setTimeZone(TimeZone.getTimeZone("IST"));
DateFormat gdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
gdf.setTimeZone(TimeZone.getTimeZone("GMT"));
//String istFormat = idf.format(date);
//System.out.println("IST: "+istFormat);
String gmtFormat = gdf.format(date);
System.out.println("GMT: "+ gmtFormat);
try {
//System.out.println("gmt parsed from istFormat: "+gdf.parse(istFormat));
//System.out.println("ist parsed from istFormat: "+idf.parse(istFormat));
System.out.println("gmt parsed from gmtFormat: "+gdf.parse(gmtFormat));
System.out.println("ist parsed from gmtFormat: "+idf.parse(gmtFormat));
} catch (ParseException e) {
e.printStackTrace();
}
String RollStart_TIMESTAMP = RollStartDATE_TIME_STAMP+" "+rolStart_TIME_STAMP;
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-mm-yyyy hh:mm");
Date parsedDate = null;
try {
parsedDate = dateFormat.parse(RollStart_TIMESTAMP);
long mili = parsedDate.getTime();
Log.e("VX:","TIMESTAMP"+mili);
} catch (ParseException e) {
e.printStackTrace();
}
Log.e("VX:","TIMESTAMP"+parsedDate);
Try this code, You get a right time stamp.
SimpleDateFormat dateFormat = new SimpleDateFormat("MMMM dd,yyyy HH:mm aaa");
timestamp = dateFormat.format(new Date()); // Find todays date
Log.e("Timestamp", timestamp);
Yes right there is wrong pattern yyyy-MM-hh is helps me out .
try {
String RollStart_TIMESTAMP = RollStartDATE_TIME_STAMP+" "+rolStart_TIME_STAMP;
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date timestamp = null;
timestamp = df.parse(RollStart_TIMESTAMP);
long ROLL_START_DATE_TIME_VALUE = timestamp.getTime()/1000;
Log.e("RX:","VALUE"+ROLL_START_DATE_TIME_VALUE);
} catch (Exception e) {
e.printStackTrace();
I'm trying to generate a time list in Java. I've read this as to how to add two times together. I wrote the code using floats before converting to using times so I know that the general format of the code works. This is the code that I'm having difficulty with:
public class Test2 {
public static void main(String[] args){
String time = "09:00";
String quarterHour = "00:15";
String halfHour = "00:30";
String quarterHour3 = "00:45";
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
Date times;
Date temp;
long sum;
try {
times = timeFormat.parse(time);
while(times.before(timeFormat.parse("15:15"))){
System.out.println("Timelist: " + time);
if((times.equals(timeFormat.parse("10:15"))) || (times.equals(timeFormat.parse("13:45")))){
temp = timeFormat.parse(halfHour);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
else if(times.equals(timeFormat.parse("11:45"))){
temp = timeFormat.parse(quarterHour3);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
else{
temp = timeFormat.parse(quarterHour);
sum = times.getTime() + temp.getTime();
time = timeFormat.format(new Date(sum));
times = timeFormat.parse(time);
}
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The result I get from that is simply 09:00. It goes through the loop once and ends.
I followed it through the debugger and what's happening is that when it adds the quarterHour to times it adds 12:15 and not the 00:15 as it's supposed to.
This seems to have something to do with me using 24 hour time as when I change the:
SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
to:
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm");
It works - except that it goes into an eternal loop.
Question: How do I get it to add only 15 minutes to the time while using 24 hour format?
Use a Calendar, or if you're using Java 8 you might use the new java.time classes like
String timeStr = "09:00";
DateFormat timeFormat = new SimpleDateFormat("HH:mm");
try {
LocalDateTime endTime = LocalDateTime.ofInstant(
Instant.ofEpochMilli(timeFormat.parse("15:15").getTime()),
ZoneOffset.ofHours(0));
Instant instant = Instant.ofEpochMilli(timeFormat.parse(timeStr)
.getTime());
LocalDateTime time = LocalDateTime.ofInstant(instant,
ZoneOffset.ofHours(0));
while (time.isBefore(endTime)) {
time = time.plus(15, ChronoUnit.MINUTES);
Instant output = time.atZone(ZoneOffset.ofHours(0)).toInstant();
System.out.println(timeFormat.format(Date.from(output)));
}
} catch (Exception e) {
e.printStackTrace();
}
or, with the Calendar like
String timeStr = "09:00";
DateFormat timeFormat = new SimpleDateFormat("HH:mm");
try {
Calendar cal = Calendar.getInstance();
cal.setTime(timeFormat.parse(timeStr));
Date when = timeFormat.parse("15:15");
while (cal.getTime().before(when)) {
cal.add(Calendar.MINUTE, 15);
System.out.println(timeFormat.format(cal.getTime()));
}
} catch (Exception e) {
e.printStackTrace();
}
Add this line to your code:
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
immediately after you declare timeFormat.
It fixes your problem on my computer.
Well i am trying to define a date and see the difference with recent date in seconds.
Below is the code i did inside onCreate method of activity:
txtNowTime = (TextView)findViewById(R.id.textViewNow);
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String currentDateandTime = formata.format(new Date());
#SuppressWarnings("deprecation")
Date oldd = new Date("07/18/2014 11:12:13");
String olddt_frmt = formata.format(oldd);
long diff =0;
try {
Date d_recent = formata.parse("currentDateandTime");
diff = d_recent.getTime() - oldd.getTime();
} catch (ParseException ex) {
ex.printStackTrace(); }
txtNowTime.setText(String.valueOf(diff));
But its not showing any result. :-(
Change this
Date d_recent = formata.parse("currentDateandTime"); to Date d_recent = formata.parse(currentDateandTime);
please find the answer
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.getDefault());
String currentDateandTime = formata.format(new Date());
long diff = 0;
try {
Date d_recent = formata.parse(currentDateandTime);
Date olddt_frmt = formata.parse("07/18/2014 11:12:13");
diff = d_recent.getTime() - olddt_frmt.getTime();
} catch (ParseException ex) {
ex.printStackTrace();
}
See this similar question using Joda-Time. Or use the new java.time package in Java 8. The old java.util.Date and .Calendar class's are notoriously troublesome and should be avoided.
Joda-Time
DateTime then = DateTime.now();
//…
DateTime now = DateTime.now();
Seconds seconds = Seconds.secondsBetween( now, then );
int secondsElapsed = seconds.getSeconds();
I get a returned parsed JSON result with string values in the form of dates like "27-11-2012" which i parse to a date Object. my code for this is:
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
//if(s.matches(""))
format = new SimpleDateFormat("dd-MMM-yyyy");
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
now my issue is, a feature has been implemented that sometimes the json only returns a year object like "2012" and is giving me an "ParseException: Unparseable date" as expected. I was thinking of using regex to match the string pattern and parse from there, but not sure how to do that. Any ideas and also anyway to parse only year in a DateFormat?
I'd try:
public Date stringToDateReport(String s){
DateFormat format;
Date date = null;
format = new SimpleDateFormat("dd-MM-yyyy");
if(s.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
//you should do a real logging here
e.printStackTrace();
}
return date;
}
The logic behind is to check if the string is only 4 long, then apply the different format. In this case, this easy method is sufficient, but in other methods, the use of regexes might be required.
Try this code
public Date stringToDateReport(String s){
//Log.d(TAG, "StringToDateReport here is " + s);
DateFormat format;
Date date = null;
if(s.indexOf("-") < 0){
format = new SimpleDateFormat("yyyy");
}else{
format = new SimpleDateFormat("dd-MMM-yyyy");
}
try {
date = (Date)format.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
Is there the possibility in have another format in the String s ? Or just these two?
public Date stringToDateReport(String strDate){
DateFormat formatnew SimpleDateFormat("dd-MM-yyyy");
Date date = null;
if(strDate.length()==4) {
format = new SimpleDateFormat("yyyy");
}
try {
date = (Date)format.parse(strDate);
} catch (ParseException e) {
//error parsing date
e.printStackTrace();
}
return date;
}
then call it like this :
String strDate = yourJson.getString("date");
Date d = stringToDateReport(strDate);