This question already has answers here:
Convert a date format in epoch
(6 answers)
Closed 6 years ago.
Is there a way to convert a given Date String into Milliseconds (Epoch Long format) in java? Example : I want to convert
public static final String date = "04/28/2016";
into milliseconds (epoch).
The getTime() method of the Date class returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
You can simply parse it to java.util.Date using java.text.SimpleDateFormat and call it's getTime() function. It will return the number of milliseconds since Jan 01 1970.
public static final String strDate = "04/28/2016";
try {
Long millis = new SimpleDateFormat("MM/dd/yyyy").parse(strDate).getTime();
} catch (ParseException e) {
e.printStackTrace();
}
You can create a Calendar object and then set it's date to the date you want and then call its getTimeInMillis() method.
Calendar c = new Calendar.getInstance();
c.set(2016, 3, 28);
c.getTimeInMillis();
If you want to convert the String directly into the date you can try this:
String date = "4/28/2016";
String[] dateSplit = date.split("/");
c.set(Integer.valueOf(dateSplit[2]), Integer.valueOf(dateSplit[0]) - 1, Integer.valueOf(dateSplit[1]));
c.getTimeInMillis();
You will need to use Calendar instance for getting millisecond from epoch
try {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date d = sdf.parse("04/28/2016");
/*
* Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
*/
System.out.println(d.getTime());
//OR
Calendar cal = Calendar.getInstance();
cal.set(2016, 3, 28);
//the current time as UTC milliseconds from the epoch.
System.out.println(cal.getTimeInMillis());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
This question already has answers here:
Why dec 31 2010 returns 1 as week of year?
(6 answers)
Closed 5 years ago.
I implemented the following method:
private int getWeek(String datum){
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
Date date = null;
try {
date = format.parse(datum);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone( "Europe/Berlin" ));
calendar.setTime(date);
int week = calendar.get(Calendar.WEEK_OF_YEAR);
return week;
}
But when I call the method with
getWeek("01.01.2017")
it returns 52. But it should be 1.
Where is my mistake?
When i call the method with
getWeek("01.01.2016")
it returns 53.
you have lost set the TimeZone in SimpleDateFormat, for example:
private int getWeek(String datum) {
TimeZone zone = TimeZone.getTimeZone("Europe/Berlin");
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
// v--- set the timezone here
format.setTimeZone(zone);
Date date = null;
try {
date = format.parse(datum);
} catch (ParseException e) {
e.printStackTrace();
}
Calendar calendar = Calendar.getInstance(zone);
calendar.setTime(date);
int week = calendar.get(Calendar.WEEK_OF_YEAR);
return week;
}
Damnit.. that was a huge brain failure.
52 is the correct answer for the input.
in Germany the first Week of Year is the first week with 4 or more days in the new year.
Sorry.
This question already has answers here:
Android/Java - Date Difference in days
(18 answers)
Closed 6 years ago.
I need to calculate number of days between two dates and I am using below code. problem is it is returning me 2 but actually it should return 3 because difference between 30 june 2016 to 27 june is 3. can you please help where it should include current date as well in difference?
public static long getNoOfDaysBtwnDates(String expiryDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
long diff = 0;
long noOfDays = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Date createdDate = new Date();
diff = expDate.getTime() - createdDate.getTime();
noOfDays = TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS);
long a = TimeUnit.DAYS.toDays(noOfDays);
// logger.info("No of Day after difference are - " + TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
System.out.println(a);
System.out.println(noOfDays);
} catch (ParseException e) {
e.printStackTrace();
}
return noOfDays;
}
expiry date is 2016-06-30 and current date is 2016-06-27
Reason is, you are not subtracting two dates with same time format.
Use Calendar class to change the time as 00:00:00 for both date and you will get exact difference in days.
Date createdDate = new Date();
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, 0);
time.set(Calendar.MINUTE, 0);
time.set(Calendar.SECOND, 0);
time.set(Calendar.MILLISECOND, 0);
createdDate = time.getTime();
More explaination in Jim Garrison' answer
Why not use LocalDate?
import java.time.LocalDate;
import static java.time.temporal.ChronoUnit.DAYS;
long diffInDays(LocalDate a, LocalDate b) {
return DAYS.between(a, b);
}
The problem is that
Date createdDate = new Date();
sets createdDate to the current instant, that is, it includes the current time as well as the date. When you parse a string using the given format, the time is initialized to 00:00:00.
Let's say you ran this at exactly 18:00 local time, you end up with
createdDate = 2016-06-27 18:00:00.000
expDate = 2016-06-30 00:00:00.000
The difference is 2 days 6 hours, not 3 days.
You should be using the newer java.time.* classes from Java 8. There is a class LocalDate that represents dates without time-of-day. It includes methods for parsing using a format, and LocalDate.now() to get the current date, as well as methods for calculating intervals between LocalDate instances.
Using the Calendar.get(Calendar.DAY_OF_MONTH) as pointed out by python:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date expDate = null;
String expiryDate ="2016-06-30";
int diff = 0;
try {
expDate = formatter.parse(expiryDate);
//logger.info("Expiry Date is " + expDate);
// logger.info(formatter.format(expDate));
Calendar cal = Calendar.getInstance();
int today = cal.get(Calendar.DAY_OF_MONTH);
cal.setTime(expDate);
diff = cal.get(Calendar.DAY_OF_MONTH)- today;
} catch (ParseException e) {
e.printStackTrace();
}
System.out.println(diff);
I have two functions which convert a date String to a date in milliseconds:
public static long convertYYYYMMDDtoLong(String date) throws ParseException {
SimpleDateFormat f = new SimpleDateFormat("yyyy-mm-dd");
Date d = f.parse(date);
long milliseconds = d.getTime();
return milliseconds;
}
If I run this function I get the following result:
long timeStamp = convertYYYYMMDDtoLong("2014-02-17");
System.out.println(timeStamp);
It prints:
1389909720000
Now, if I run the following code:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeStamp);
System.out.println(cal.getTime());
It prints out:
Fri Jan 17 00:02:00 IST 2014
Why is my date shifted by one month? What is wrong?
P.S: My problem is that I need to map the date, represented as long, to another third party API which accepts Calendar format only.
You're using mm, which is minutes, not months. You want yyyy-MM-dd as your format string.
It's not clear why you're not returning a Calendar directly from your method, mind you:
private static final TimeZone UTC = TimeZone.getTimeZone("Etc/UTC")
public static Calendar convertYYYYMMDDtoCalendar(String text) throws ParseException {
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
format.setTimeZone(UTC);
Calendar calendar = new GregorianCalendar(UTC);
calendar.setDate(format.parse(text));
return calendar;
}
(That's assuming you want a time zone of UTC... you'll need to decide that for yourself.)
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;
This question already has answers here:
Date object to Calendar [Java]
(8 answers)
Closed 6 years ago.
So I get a date attribute from an incoming object in the form:
Tue May 24 05:05:16 EDT 2011
I am writing a simple helper method to convert it to a calendar method, I was using the following code:
public static Calendar DateToCalendar(Date date )
{
Calendar cal = null;
try {
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
cal=Calendar.getInstance();
cal.setTime(date);
}
catch (ParseException e)
{
System.out.println("Exception :"+e);
}
return cal;
}
To simulate the incoming object I am just assigning the values within the code currently using:
private Date m_lastActivityDate = new Date();
However this is givin me a null pointer once the method reaches:
date = (Date)formatter.parse(date.toString());
Here's your method:
public static Calendar toCalendar(Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
Everything else you are doing is both wrong and unnecessary.
BTW, Java Naming conventions suggest that method names start with a lower case letter, so it should be: dateToCalendar or toCalendar (as shown).
OK, let's milk your code, shall we?
DateFormat formatter = new SimpleDateFormat("yyyyMMdd");
date = (Date)formatter.parse(date.toString());
DateFormat is used to convert Strings to Dates (parse()) or Dates to Strings (format()). You are using it to parse the String representation of a Date back to a Date. This can't be right, can it?
Just use Apache Commons
DateUtils.toCalendar(Date date)
it's so easy...converting a date to calendar like this:
Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();