I'm trying to convert a date with epoch time method.
with these code below
long epoch = 0;
try {
epoch = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss").parse("12/11/2017 23:20:23")
.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
It gives me the epoch time: 1513052423
Which once convert give: Tuesday 12 December 2017 04:20:23 and not 23:20:23 :/
According to documentation SimpleDateFormat is locale-sensitive. Please check or set your timezone
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
Related
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();
}
I try to parse a Date from a String:
String dateString = "Fr, 1. Jan";
DateFormat format = new SimpleDateFormat("EE, d. MMM");
Date date = null;
try {
date = format.parse(dateString);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(format.format(date));
And what I got as output is these:
Do, 1. Jan
Why did that happen and why isn't it the same output as the input?
You forgot the year. When you parse it, you will get in the year 1970 (the Friday will be ignored). When you parse back, you will parse the date 01 Jan 1970, which was a Thursday. This should work:
String dateString = "Fr, 1. Jan";
DateFormat format = new SimpleDateFormat("EE, d. MMM");
Date date = null;
try {
date = format.parse(dateString);
} catch (Exception e) {
e.printStackTrace();
}
date.setYear(new Date().getYear()); //alternativ: date.setYear(2016);
System.out.println(date);
System.out.println(format.format(date));
A Date in Java begins at 01-01-1970. The 1st January in 1970 was a Thursday, therefore it parses the day as Thursday instead of Friday. You would have to add a year in order to guarantee that it's a Friday.
"Do" is the first 2 letters of "Donnerstag", which is German for "Thursday". Judging by your last name "Baum" (German for "tree"), I'm guessing that is not a coincidence. Also, 1970-01-01 was a Thursday, and if you don't specify the year, you get start-of-epoch.
The date format "E" is the day-of-week as a word - the more "E"'s you specify, the more letters of that word get rendered; "EE" would render "Thursday" as "Do" in a German locale, which is suspect is your default locale.
Your code as-is explodes for me, but this similar code produces the same output you get:
String dateString = "Fri, 1. Jan";
DateFormat format = new SimpleDateFormat("EEE, d. MMM");
Date date = format.parse(dateString);
DateFormat format2 = new SimpleDateFormat("EE, d. MMM", Locale.GERMAN);
System.out.println(format2.format(date));
Output:
Do, 1. Jan
I'm just doing a simple difference of two timemilisseconds of two different calendar.
Example:
Calendar ini = Calendar.getInstance();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {e.printStackTrace();}
Calendar end = Calendar.getInstance();
long diff = end.getTimeInMillis()-ini.getTimeInMillis();
System.out.println("diff "+diff);
System.out.println("ini date "+ ini.getTime());
System.out.println("end date "+ end.getTime());
System.out.println("diff time format "+timeFormat.format(diff));
The time format is:
private final static String TIME_STRING_FORMAT = "hh:mm:ss.SSS";
private static SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_STRING_FORMAT);
And in the output, always appear 1 our of difference, is it problem of the SimpleDateFormat???
Output:
diff 1500
ini date Sun May 24 22:27:01 CEST 2015
end date Sun May 24 22:27:03 CEST 2015
diff time format 01:00:01.500
Thanks for your help!!
It looks like SimpleDateFormat uses a timezone. See this related question. So when you give it the time 1500 milliseconds, it thinks you're giving it the time since the beginning of epoch time in the GMT time. Then it translates this to your timezone, giving you some hours of offset. You probably want to set the timezone on your timeFormat to GMT. Try this:
Calendar ini = Calendar.getInstance();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {e.printStackTrace();}
Calendar end = Calendar.getInstance();
long diff = end.getTimeInMillis()-ini.getTimeInMillis();
System.out.println("diff "+diff);
System.out.println("ini date "+ ini.getTime());
System.out.println("end date "+ end.getTime());
Date date = new Date(diff);
System.out.println(date);
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
System.out.println("diff time format "+timeFormat.format(date));
The 1 hour difference is caused by your local time zone. Date(long) constructs a date a number of milli seconds after January 1st 1970 GMT. In continental Europe (during winter) 1500 milli seconds after the epoch is thus January 1st 01:00:01.500.
If you use Java 8 see the tutorial on Period and Duration. Duration is probably what you want to use.
i am converting string in to date object in android......
that string is coming from server in form of "2014-02-22" or something like that... i want to convert it in to my date which i can use in my application..
i am using Simple Date Format ,parse method to convert....
but this statement throws parse exception... meaning its not converting my string.. which is "2014-02-22"...
it should convert but its not....
so kindly help me in this..... i am getting null in response
#SuppressLint("SimpleDateFormat")
public static Date getDate(String string){
Date date = null;
try {
date = new Date();
date = new SimpleDateFormat("yyyy/MM/dd").parse(string);
}
catch (ParseException e) { e.printStackTrace(); }
catch (java.text.ParseException e) { e.printStackTrace(); }
return date;
}
Try as follows...
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date;
#SuppressLint("SimpleDateFormat")
public static Date getDate(String string){
date = new Date();
try {
date = format.parse(string);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date testDate = null;
try {
testDate = sdf.parse("2013-11-12");
}
catch(Exception ex) {
ex.printStackTrace();
}
int date= testDate.getDate();
int month = testDate.getMonth();
int year = testDate.getYear();
Just use SimpleDateFormat (click the link to see all format patterns).
String string = "2014-02-22";
Date date = new SimpleDateFormat("yyy-M-d", Locale.ENGLISH).parse(string);
System.out.println(date); // Sat Jan 02 00:00:00 BOT 2010
Here's an extract of relevance from the javadoc, listing all available format patterns:
G Era designator Text AD
y Year Year 1996; 96
M Month in year Month July; Jul; 07
w Week in year Number 27
W Week in month Number 2
D Day in year Number 189
d Day in month Number 10
F Day of week in month Number 2
E Day in week Text Tuesday; Tue
u Day number of week Number 1
a Am/pm marker Text PM
H Hour in day (0-23) Number 0
k Hour in day (1-24) Number 24
K Hour in am/pm (0-11) Number 0
h Hour in am/pm (1-12) Number 12
m Minute in hour Number 30
s Second in minute Number 55
S Millisecond Number 978
z Time zone General time zone Pacific Standard Time; PST; GMT-08:00
Z Time zone RFC 822 time zone -0800
X Time zone ISO 8601 time zone -08; -0800; -08:00
I got simple code, maybe the problem relies on the given format string or on the timezone. So here is the code:
public static void main(String[] args) {
SimpleDateFormat df = new SimpleDateFormat("HH:mm");
try {
Date added = df.parse("00:00");
System.out.println(added);
System.out.println(added.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The result is:Thu Jan 01 00:00:00 EET 1970
-10800000 --> should be 0 as we give 00:00 hours in and the other time elements remain default.
//Edit
Yes the problem is with timezone to fix this use
df.setTimeZone(TimeZone.getTimeZone("UTC")); before parsing.
The value 10800000 is exactly 3 hours (in milliseconds), which I'm gathering is roughly the offset between EET and UTC (actually, it's only 2 hours according to this, but I guess the extra hour's down to DST or something).
Therefore, the difference is probably due to your timezone.
Your timezone appears to be EET. That difference would be the offset from 1st Jan 1970 00:00:00.000 UTC
Since you didn't specify the date, only the hour, you actually created a Date object with default values, as specified in the DateFormat API (which SimpleDateFormat implements):
The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT.