I am converting java Date object to epoch using code :
String str = "" + date;
SimpleDateFormat df = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss.SSS");
Date formateDate = df.parse(str);
long epoch = formateDate.getTime();
return epoch;
If I test this with value 2013-04-26 08:34:55.705 then it gives Long as 1359189295705 which is actually Sat, 26 Jan 2013 08:34:55 GMT but its Friday today why does it say that its Saturday on 26th January 2013.
It's using January not April. January 26th was indeed a Saturday. It's given you the wrong month because your date format is wrong:
yyyy-mm-dd HH:mm:ss.SSS
You're using mm for the month, when you should be using MM. The date format should be:
yyyy-MM-dd HH:mm:ss.SSS
Your format didn't specify the month anywhere, so presumably it just defaulted to January.
The format for month is wrong, should be yyyy-MM-dd, so it's defaulting to the first month for you.
Related
I want to convert a date to GMT.
I get a date in BST, I want to convert it to GMT without time zone conversion.
Example:
**If the BST date is: Wed June 26 13:30:13 BST 2019
I want to convert it to Wed 26 Jun 2019 13:30:13 GMT**
I want to ignore the timezone info and return the same date as GMT.
For this I am trying
private SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
private SimpleDateFormat dateFormatGmtText = new SimpleDateFormat("EEE dd MMM yyyy HH:mm:ss 'GMT'");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
String textDate = dateFormatLocal.format(date);
//Date is Wed June 26 13:30:13 BST 2019
private Date toGMTDate(final Date date) {
String textDate = dateFormatLocal.format(date);
try {
String[] dateParts = textDate.split("\\+");
textDate = dateParts[0] + "+0000";
return dateFormatGmt.parse(textDate);
} catch (ParseException e) {
return null;
}
}
private String toGMT(final Date date) {
return dateFormatGmtText.format(toGMTDate(date));
}
When I call toGMT it returns Wed 26 Jun 2019 14:30:13 GMT
I am not sure why it is so?
What is wrong here?
java.time
You said you can’t use the modern date and time API, but for other readers I should like to present that option first. SimpleDateFormat and Date are poorly designed and long outdated, the former in particular notoriously troublesome, so I recommend avoiding them.
I am assuming that BST is for British Summer Time (other interpretations exist). And I am assuming that you cannot avoid getting an old-fashioned Date object.
private static DateTimeFormatter formatter
= DateTimeFormatter.ofPattern("EEE dd MMM yyyy HH:mm:ss z", Locale.UK);
private static ZoneId britain = ZoneId.of("Europe/London");
private static ZoneId gmt = ZoneId.of("Etc/GMT");
private static String toGMT(final Date date) {
ZonedDateTime britishTime = date.toInstant().atZone(britain);
ZonedDateTime gmtTime = britishTime.withZoneSameLocal(gmt);
return gmtTime.format(formatter);
}
Try it out with your Date of Wed Jun 26 13:30:13 BST 2019:
String textDate = dateFormatLocal.format(date);
System.out.println(textDate);
System.out.println(toGMT(date));
Output is:
2019-06-26T13:30:13+0100
Wed 26 Jun 2019 13:30:13 GMT
Whenever you get an old-fashioned Date, the first thing to do is to convert it to Instant. Then do any further conversions from there. The key to changing time zone and keeping the date and time of day (hour-minute-second of day) is the withZoneSameLocal method of the ZonedDateTime class.
I recommend specifying locale for the formatter.
I am not sure why it is so? What is wrong here?
A Date hasn’t got, as in cannot have a time zone. It’s a point in time, nothing more. YourtoGMTDate method returns a point in time that is an hour later: The time you gave it was 13:30:13+0100, and it returned 13:30:13+0000, which is the same point in time as 14:30:13+0100. Next you formatted this point in time using a formatter that used your default time zone, Europe/London, and therefore produced 14:30:13, but at the same time printed GMT in the string — the result you reported.
…the new time library, but for some reasons I can't use them.
If you really have got an evil boss that either forces you to use Java 1.4 or 1.5 and/or forbids the use external dependencies, the pretty simple hack is:
private String toGMT(final Date date) {
return dateFormatGmtText.format(date);
}
The cheating is: Your dateFormatGmtText uses your default time zone, Europe/London, but lies and prints GMT in the formatted string. This gives the same output as above — the output you asked for. Compared to your code I am just leaving out the date conversion.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I am using the following method to return a formatted date as say 07:00AM, Apr 12 2016. But I keep getting 01:41PM, Sat, Jan 17 1970. Say for example my timestamp is 1460469600.
Here is my method.
public static String formattedDate(long timestamp) {
DateTime date = new DateTime(timestamp);
String formatted= date.toString("hh:mma, EEE, MMM dd yyyy");
return formatted;
}
Your timeStamp is wrong. It doesnt represent the correct time in millis. YOur timeStamp refers to 01:41PM, Sat, Jan 17 1970.
You can check what time date the timeinmillis (TimeStamp) refers to from this site.
http://currentmillis.com/
To get the correct time from unix time stamp just change your DateTime date = new DateTime(timestamp); into
DateTime date = new DateTime(timestamp*1000);
Because unix time gives timpestamp in seconds and we need millis here.
Query to get timestamp in milliseconds :
select UNIX_TIMESTAMP(yourtimestamp) *1000 from tablename.
this gives time stamp in milliseconds in mysql
I am using an API to get a weather forecast up until a particular date in Java.
The requirement for passing a date as a URL parameter is that it must be in "YYYY-MM-DD'T'HH:MM:SS" format. I get input in this format from the user, then get the current system date, and then loop until the desired date. The problem lies in converting the input date string into the date format, incrementing it by one day, and then converting it back to the string format for URL parameter.
I am using the following code to do this but it is giving me incorrect results:
formatter = new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");
Date date1 = formatter.parse(inputtime);
System.out.println(date1);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
c1.add(Calendar.DAY_OF_MONTH, 1); // number of days to add
inputtime = formatter.format(c1.getTime()); // dt is now the new date
System.out.println(c1.getTime());
System.out.println(inputtime);
inputtime is the input by the user. If I give "2014-04-12T00:00:00" as inputtime, date1 is then "Sun Dec 29 00:00:00 PKT 2013", c1.getTime() returns "Mon Dec 30 00:00:00 PKT 2013" and inputtime becomes then "2014-12-364T00:12:00" according to the above code block.
How can this logic error be corrected?
You should consider SimpleDateFormat date and time patterns: link
For example, something like this:
formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Have a try to change your date pattern from
new SimpleDateFormat("YYYY-MM-DD'T'HH:MM:SS");
to
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Letter Date or Time Component Presentation Examples
y Year Year 1996; 96
M Month in year Month July; Jul; 07
D Day in year Number 189
d Day in month Number 10
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
The java.util.Date and .Calendar classes bundled with Java are notoriously troublesome. Avoid them.
That format is defined by the ISO 8601 standard. The Joda-Time library follows that standard's formats as a default for both parsing and generating strings. So does the new java.time package in Java 8.
Your string omits a time zone offset. So, you need to know and specify the time zone intended by that string. Perhaps the time zone is UTC meaning a time zone offset of zero.
A day is not always 24 hours. If you meant 24 hours rather than 1 day, call the method plusHours( 24 ).
Here is example code in Joda-Time 2.3.
String input = "2014-01-02T03:04:05";
DateTimeZone timeZone = DateTimeZone.UTC;
DateTime dateTime = new DateTime( input, timeZone );
DateTime tomorrow = dateTime.plusDays( 1 );
String outputWithOffset = tomorrow.toString();
String output = ISODateTimeFormat.dateHourMinuteSecond().print( tomorrow );
I'm working with the following snippet which takes a datetime as a string, then creates a Date object from it:
Date currentDate = new Date();
SimpleDateFormat f = new SimpleDateFormat("EEEE, MMMM d 'at' h:mm a");
currentDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2014-03-06 12:59:01");
System.out.println(f.format(currentDate));
The last two lines give an output of "Thursday, March 6 at 12:59 AM", but it should be PM. What is causing this? It only happens for the noontime am/pm switch. For example if the time being parsed was ("2014-03-06 00:59:01") the output is correctly "Thursday, March 6 at 12:59 AM". Thanks in advance for your help!
This line
currentDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse("2014-03-06 12:59:01");
contains hh which is the 1-12 hour format. Try using capital HH, which uses 0-23 format.
"yyyy-MM-dd HH:mm:ss"
Output:
Thursday, March 6 at 12:59 PM
The date formatting symbols and descriptions are in the SimpleDateFormat javadocs.
I have Date today=new Date(); which returns the current date.. but when i try to display date,month,year separately with the help of
DateFormat mmFormat=new SimpleDateFormat("MM");
System.out.println(mmFormat.format(today.getMonth()));
DateFormat yyFormat=new SimpleDateFormat("yyyy");
System.out.println(yyFormat.format(today.getYear()));
it prints month as 01 and year as 1970
how to resolve this.?
mmFormat.format(today.getMonth())
You're passing an integer – the month of the date – to a date format method.
The format method interprets that integer as a UNIX timestamp – a number of seconds since 1970.
You need to pass the date itself to the formatter.
Pass the entire date to SimpleDateFormat. The format string "MM" or "yyyy" will cause it to just extract the part of the date you want.
Just use the Date today as the input argument
System.out.println(mmFormat.format(today));
and
System.out.println(yyFormat.format(today));
today.getMonth() and today.getYear() returns an int which is interpreted as an UNIX timestamp . The value is 1 and 113 , which corresponds to approximately January 1, 1970, 00:00:01 GMT and January 1, 1970, 00:01:53 GMT represented by this Date object. To get the desired result , you need to pass the Date object :
System.out.println(mmFormat.format(today));
You would need to use Calendar. Have a look at the java docs.
You can do it like this -
Calendar cal = Calendar.getInstance();
System.out.println(cal.get(Calendar.DAY_OF_MONTH));
System.out.println(cal.get(Calendar.MONTH)); // month in the Calendar class begins from 0
System.out.println(cal.get(Calendar.YEAR));
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
System.out.println(cal.get(Calendar.MINUTE));
System.out.println(cal.get(Calendar.SECOND));
This would help you to avoid creating multiple DateFormat objects. Also in case you want to use another date instead of today's date the you can just pass the date to the cal.setTime() method.
That is because all these methods are deprecated. Use
Calendar myCalendar = GregorianCalendar.getInstance();
myCalendar.get(Calendar.MONTH);
myCalendar.get(Calendar.YEAR);
myCalendar.get(Calendar.DAY_OF_MONTH);
Better in this way
Date date=new Date(); // your date
Calendar cal = Calendar.getInstance();
cal.setTime(date);
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
System.out.println(year+"\n"+month);