I have a log in timeformat
31/Mar/2013:17:03:30 -0700
I want to convert it into a timestamp here -70 in timezone. How can I do that?
try {
String time = myMap.get("timestamp");
String splitTime[] = time.split("-");//input Timestamp 31/Mar/2013:17:03:30 -0700
Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss").parse(splitTime[0]);
myMap.put("timestamp", String.valueOf(new Long(date.getTime() / 1000)));
} catch (ParseException e) {
e.printStackTrace();
}
How do I use this timezone?
try this
Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z").parse(s);
note that it will only parse /Mar/ if your default language is English, otherwise use
Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss Z", Locale.US).parse(s);
Well you can use that time zone information to subtract/add that much time to your date:
String time = myMap.get("timestamp");
String splitTime[] = time.split("-");//input Timestamp 31/Mar/2013:17:03:30 -0700
Date date = new SimpleDateFormat("dd/MMM/yyyy:HH:mm:ss").parse(splitTime[0]);
long timestamp = date.getTime() / 1000; ///datetime in seconds
long timezonehour = Long.parseLong(splitTime[1].substring(0,1)); // 07
long timezoneminutes = Long.parseLong(splitTime[1].substring(2,3)); // 00
timezonehour += timezoneminutes/60;
long timezone_seconds = (timezonehour/60)/60; // in seconds
timestamp += timezone_seconds // final computed value
I know this looks ugly but can't help further.
Related
I have two date time string, one is current time and second is given as follows.
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Now I want to check if the endTime has passed currentTime.
Thanks
Take a look at
this and this
Example:
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyyHH:mm:ss");
try {
Date currentTimeDate = sdf.parse("05/30/2018 16:56:21");
Date endTimeDate = sdf.parse("05/30/2018 16:59:21");
currentTimeDate.compareTo(endTimeDate); // false / current time has not passed end time.
endTimeDate.compareTo(currentTimeDate); // true / end time has passed current time.
} catch (ParseException ignored) {
}
Convert both strings to Date object and then use before() method to check if the end time has passed currentTime.
String currentTime = "05/30/2018 16:56:21";
String endTime = "05/30/2018 16:59:21";
Date current=new SimpleDateFormat("dd/MM/yyyy").parse(currentTime);
Date end=new SimpleDateFormat("dd/MM/yyyy").parse(endTime);
if(end.before(current)) {
// end time has passed currenctTime
} else {
// no
}
Keep both times in milliseconds which is a long value
long currentTime= System.currentTimeMillis();
You can also convert your and time in millies using below code.
String givenDateString = "Tue Apr 23 16:08:28 GMT+05:30 2013";
SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
try {
Date mDate = sdf.parse(givenDateString);
long endTime= mDate.getTime();
System.out.println("Date in milli :: " + endTime);
} catch (ParseException e) {
e.printStackTrace();
}
Now compare, if current time is larger then end time, thus current time has passed end time like below.
if(currentTime>endTime){
//Do stuff
}
Enjoy..
I would like to calculate the time difference between two days (e.g. Friday and Saturday) of the same week. This sort of calculation is required for validating a time restriction of my project. To understand more about the restriction see the below examples,
Example 1
{
"id": "3",
"from_day": "Fri",
"from_time": "16:00:00",
"to_day": "Sat",
"to_time": "06:00:00"
}
Example 2
{
"id": "4",
"from_day": "Mon",
"from_time": "04:00:00",
"to_day": "Mon",
"to_time": "09:00:00"
}
From the above example I've to verify if the running application passes between the exact date and time of the same week.
What I've done so far?
I've created this simple function which takes the "day of week" e.g Mon, "from time" e.g 04:00:00 and "to time" e.g 09:00:00 as parameter and returns if it's within the range.
public boolean getValidity(String day, String dateStart, String dateStop) {
Calendar calendar = Calendar.getInstance();
Date date = calendar.getTime();
String current_day = new SimpleDateFormat("EE", Locale.ENGLISH)
.format(date.getTime());
if (current_day.matches(day)) {
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
Date today = Calendar.getInstance().getTime();
String datePresent = format.format(today);
Date d1 = null;
Date d2 = null;
Date d3 = null;
try {
d1 = format.parse(dateStart);
d2 = format.parse(dateStop);
d3 = format.parse(datePresent);
} catch (Exception e) {
e.printStackTrace();
}
long current_time = d3.getTime();
long start_time = d1.getTime();
long stop_time = d2.getTime();
if (current_time >= start_time && current_time <= stop_time) {
return true;
} else {
return false;
}
}
return false;
}
// this function is used for converting the time into GMT +8 before passing as a parameter in the getValidity() function
public String toGMT(String time){
//first convert the received string to date
Date date = null;
//creating DateFormat for converting time from local timezone to GMT
DateFormat format = new SimpleDateFormat("HH:mm:ss", Locale.ENGLISH);
try {
date = format.parse(time);
} catch (ParseException e) {
e.printStackTrace();
}
//getting GMT timezone, you can get any timezone e.g. UTC
format.setTimeZone(TimeZone.getTimeZone("GMT+8"));
return format.format(date).toString();
}
But the above code doesn't works for the first example where the dates are different. It would be extremely helpful if anyone can give some idea of solving the issue.
You can turn a date object into a long (milliseconds since Jan 1, 1970), and then use TimeUnit to get the number of seconds:
long diffInMs = endDate.getTime() - startDate.getTime();
long diffInSec = TimeUnit.MILLISECONDS.toSeconds(diffInMs);
end date and start date as date object for your days which you can do self.
I am able to get all user feed to facebook graph api in my android app. Following is date string from updated_time key :
2014-12-14T18:23:17+0000
First I wasn't able to find format for this string. From google I only come to know, this is might be RFC 2822 date format.
I want to convert this date string to unix time stamp to fetch new user feeds. How can I convert this string to unix time stamp?
If I try to parse this string using following formate I'm getting null date:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
It is advised to strip the +0000 from the date as this is the timezone information. Then handling the timezone separately i.e. as an integer you can either add or subtract it from the time in millis by multiplying the timezone stripped and converting it to milliseconds.
public static long getDateInMillis(String srcDate) {
try {
SimpleDateFormat desiredFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
long dateInMillis = 0;
try {
Date date = desiredFormat.parse(srcDate);
dateInMillis = date.getTime();
return dateInMillis;
} catch (ParseException e) {
e.printStackTrace();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return 0;
}
Your format pattern is wrong.
String timeStamp = "2014-12-14T18:23:17+0000";
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.ENGLISH);
System.out.println("Unix timestamp: " + dateFormat.parse(timeStamp).getTime());
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating the Difference Between Two Java Date Instances
i have two date values in two textboxes in string datatypes in HH:MM:SS format.HOw can i find difference between them and get result in HH:MM:SS?please help me...as fast as possible....!
Try this:
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
format.setTimeZone(TimeZone.getTimeZone("UTC"));
try {
Date date1 = (Date) format.parse("4:15:20");
Date date2 = (Date) format.parse("2:30:30");
//time difference in milliseconds
long timeDiff = date1.getTime() - date2.getTime();
//new date object with time difference
Date diffDate = new Date(timeDiff);
//formatted date string
String timeDiffString = format.format(diffDate);
System.out.println("Time Diff = "+ timeDiffString );
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Above code has certain limitations. Other proper way could be to convert the long value of time difference manually in the string as below:
long timeDiffSecs = timeDiff/1000;
String timeDiffString = timeDiffSecs/3600+":"+
(timeDiffSecs%3600)/60+":"+
(timeDiffSecs%3600)%60;
System.out.println("Time Diff = "+ timeDiffString);
The code you have will give you the number of milliseconds difference between the listed dates. It could be that the answer could be simply divide by 1000 to get the number of seconds.
First Convert String date into simple Date formate
public String getconvertdate1(String date)
{
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
inputFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
DateFormat outputFormat = new SimpleDateFormat("dd MMM yyyy");
Date parsed = new Date();
try
{
parsed = inputFormat.parse(date);
}
catch (ParseException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String outputText = outputFormat.format(parsed);
return outputText;
}
//now can do anything with date.
long diff = today.getTimeInMillis() - thatDay.getTimeInMillis(); //result in millis
long days = diff / (24 * 60 * 60 * 1000);// you get day difference between
AND use simpledateFormate to configure HH:MM:SS
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Calculate date/time difference in java
how would a future date such as Sat Feb 17 2012 be converted into milliseconds in java that can then be subtracted from the current time in milliseconds to yield time remaining until that future date.
The simplest technique would be to use DateFormat:
String input = "Sat Feb 17 2012";
Date date = new SimpleDateFormat("EEE MMM dd yyyy", Locale.ENGLISH).parse(input);
long milliseconds = date.getTime();
long millisecondsFromNow = milliseconds - (new Date()).getTime();
Toast.makeText(this, "Milliseconds to future date="+millisecondsFromNow, Toast.LENGTH_SHORT).show();
A more difficult technique (that basically does what DateFormat does for you) involves parsing it yourself (this would not be considered best practice):
String input = "Sat Feb 17 2012";
String[] myDate = input.split("\\s+");
int year = Integer.parseInt(myDate[3]);
String monthString = myDate[1];
int mo = monthString.equals("Jan")? Calendar.JANUARY :
monthString.equals("Feb")? Calendar.FEBRUARY :
monthString.equals("Mar")? Calendar.MARCH :
monthString.equals("Apr")? Calendar.APRIL :
monthString.equals("May")? Calendar.MAY :
monthString.equals("Jun")? Calendar.JUNE :
monthString.equals("Jul")? Calendar.JULY :
monthString.equals("Aug")? Calendar.AUGUST :
monthString.equals("Sep")? Calendar.SEPTEMBER :
monthString.equals("Oct")? Calendar.OCTOBER :
monthString.equals("Nov")? Calendar.NOVEMBER :
monthString.equals("Dec")? Calendar.DECEMBER : 0;
int day = Integer.parseInt(myDate[2]);
Calendar c = Calendar.getInstance();
c.set(year, mo, day);
long then = c.getTimeInMillis();
Time current_time = new Time();
current_time.setToNow();
long now = current_time.toMillis(false);
long future = then - now;
Date d = new Date(future);
//TODO use d as you need.
Toast.makeText(this, "Milliseconds to future date="+future, Toast.LENGTH_SHORT).show();
Firts, you must parse you String to get its Date representation. Here are examples and some docs.
Then you shoud call getTime() method of your Date.
DateFormat format = new SimpleDateFormat("EEE MMM dd yyyy", Locale.US);
long futureTime = 0;
try {
Date date = format.parse("Sat Feb 17 2012");
futureTime = date.getTime();
} catch (ParseException e) {
Log.e("log", e.getMessage(), e);
}
long curTime = System.currentTimeMillis();
long diff = futureTime - curTime;
Pass year, month and day of the future date in the date of this code and variable diff will give the millisecond time till that date,
Date date = new GregorianCalendar(year, month, day).getTime();
Date today = new Date();
long diff = date.getTime() - today.getTime();
You can simply call the getTime() method of date object. please follow through the sample below
import java.util.Date;
public class Test {
#SuppressWarnings("deprecation")
public static void main(String[] args) {
System.out.println(new Date("Sat Feb 17 2012").getTime());
}
}
try { String str_date="11-June-07";
SimpleDateFormat formatter ;
Date date ;
formatter = new SimpleDateFormat("dd-MMM-yy");
date = (Date) formatter.parse(str_date);
Log.i("test",""+date);
} catch (Exception e)
{System.out.println("Exception :"+e); }
Date d = new Date();
long time = d.getTime();
long timeDiff = time - lastTime;
//timeDiff will contain your value.
//import these two,
//import java.text.SimpleDateFormat;
//import java.util.Date;