I want to convert date from this format to Tue Sep 08 14:27:00 IST 2015 to 2015-09-08T14:27:00-0500 how to do this with SimpleDateFormat?
I tried like this way
Calendar cl = Calendar.getInstance();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
ft.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
ft.format(cl.getTime());
the above code giving output 2015-09-08T04:57:00-0400 but I want to change only timezone and it should be -0500
How could I do this?
SimpleDateFormat uses a Calendar instance to work with Dates. If you change the timezone, the timezone of this Calendar instance is changed. If you really want to change only the output - in your case the timezone, without changing the Time (i do not know why you want to do this, but i assume you have a reason), you could do something like this:
Calendar cl = Calendar.getInstance();
TimeZone tz = TimeZone.getTimeZone("US/Eastern");//TimeZone.getDefault();
int offset = tz.getRawOffset();
String offsetStr = ((offset < 0) ? "-" : "+") + String.format("%02d%02d",
Math.abs(offset / 3600000), (offset / 60000) % 60);
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'" + offsetStr+"'");
String dt = ft.format(cl.getTime());
use:
ft.setTimeZone(TimeZone.getTimeZone("GMT-5"))
sample:
Calendar cl = Calendar.getInstance();
SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
ft.setTimeZone(TimeZone.getTimeZone("US/Eastern"));
System.out.println(ft.format(cl.getTime()));
ft.setTimeZone(TimeZone.getTimeZone("GMT-5"));
System.out.println(ft.format(cl.getTime()));
produces:
2016-03-23T16:39:22-0400
2016-03-23T15:39:22-0500
source: https://docs.oracle.com/javase/6/docs/api/java/util/TimeZone.html
Below code is working fine for me
Calendar cl = Calendar.getInstance();
ZoneOffset offset = ZoneOffset.of(ZoneId.SHORT_IDS.get("EST"));
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'"+offset.getId()+"'");
formatter.format(cl.getTime());
Related
I am working on codename one project and I am struggling to convert device time to UTC.
I use this code :
Calendar cal = Calendar.getInstance();
System.out.println(cal.getTimeZone());
TimeZone tzUTC = TimeZone.getTimeZone("UTC");
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a z");
dtfmt.setTimeZone(tzUTC);
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
and codename one reject the setTImeZone method.
I use java.text.DateFormat but when I run it, condename one cant compile it also.
It may not really answer your real question, but the following works for me:
Calendar cal = Calendar.getInstance();
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.LONG);
TimeZone tzUtc = TimeZone.getTimeZone("UTC");
df.setTimeZone(tzUtc);
System.out.println("UTC: " + df.format(cal.getTime()));
I don’t know com.codename1.l10n.DateFormat, so I’m sorry I cannot help you there.
Use:
java.util.Calendar cal = java.util.Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
cal.setTime(new Date(System.currentTimeMillis() - tz.getRawOffset()));
com.codename1.l10n.DateFormat dtfmt = new com.codename1.l10n.SimpleDateFormat("EEE, yyyy-MM-dd KK:mm a");
System.out.println("UTC: " + dtfmt.format(cal.getTime()));
Then append UTC to the string as the value is always UTC.
Was using Shai's solution but noticed that it wasn't giving the correct UTC time when the device timezone was in daylight savings time. Below is a more general solution using tz.getOffset() instead of tz.getRawOffset(). Seems like there should be simpler way!
L10NManager l10n = L10NManager.getInstance();
long sysRtnTime = System.currentTimeMillis() / 1000L;
Date errorDate = new Date(sysRtnTime * 1000L);
Date currentDate = new Date();
String deviceTime = l10n.formatDateTime(errorDate);
Calendar c = Calendar.getInstance();
long unixtime = errorDate.getTime();
TimeZone tz = c.getTimeZone();
// to get offset, we need era, year, month, day, dayOfWeek,millis
SimpleDateFormat yearFormat = new SimpleDateFormat("yyyy");
SimpleDateFormat monthDateFormat = new SimpleDateFormat("MM");
SimpleDateFormat dayDateFormat = new SimpleDateFormat("dd");
SimpleDateFormat dayOfWeekDateFormat = new SimpleDateFormat("F");
SimpleDateFormat millisDateFormat = new SimpleDateFormat("S");
int year = Integer.parseInt(yearFormat.format(currentDate));
int month = Integer.parseInt(monthDateFormat.format(currentDate));
int day = Integer.parseInt(dayDateFormat.format(currentDate));
int dayOfWeek = Integer.parseInt(dayOfWeekDateFormat.format(currentDate));
int millis = Integer.parseInt(millisDateFormat.format(currentDate));
// c.setTime(new Date(unixtime - tz.getRawOffset())); // c in UTC only if device not DST
month = month - 1; // since getOffset assume 0 = Jan and 11 = Dec
c.setTime(new Date(unixtime - tz.getOffset(1, year, month, day, dayOfWeek, millis))); // c in UTC (even if device in DST)
Date cDateUTC = c.getTime(); // sDate in UTC
String timeInUTC = serverDateFormat.format(cDateUTC);
Log.p("Time (in device timezone): " + deviceTime);
Log.p("Time (in UTC): " + timeInUTC);
I am writing in a CSV and my calendar is doubling values ... I couldn't figure out the problem.
PS: Amount is like 1.000.000 or 10.000.000.
public static void CSV(String path, int amount) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar c = Calendar.getInstance();
c.set(1980, 01, 01);
for (; set.size() < amount;) {
c.set(Calendar.MINUTE, c.get(Calendar.MINUTE) + 2);
set.add(c.getTime());
}
Iterator<Date> it = set.iterator();
for (int i = 0; i < amount; i++) {
csvWriter.append(dateFormat.format(it.next()));
}
...
}
Well, the error was the Hour in am/pm (1-12).
Thanks to #Teemu.
I assume you mean "doubling values" by that the same time occurs twice. Reason for that is your date formatter:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
You are formatting hours as 'hh'. Meaning that it is formatting date as Hour in am/pm (1-12) . So two time values are actually unique, one is AM and another is PM. You are not providing the AM / PM markings into SimpleDateFormat and that's why both time values looks the same.
If you want to distinquish the AM / PM markings change the format to this:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss aaa");
Or another way is to format hours in 0-23 format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Not sure if my assumption is correct but I hope this helps.
I have SAS date objects stored as integer and they look like : 19725.
I am trying to write java code to convert the date to YYYY-MM-DD
I see in the documentation that the SAS date value is the number of days from 01 Jan 1960
For example:
02 Jan 1960 would return 1
04 June 2003 would return 15680
Could you give the java code for this conversion. ie. convert something like 19725 to the date format : YYYY-MM-DD
I try the logic below but 15680 gives 2003-01-06 and not 2003-06-04 as the output. Could anyone point the mistake.Thanks in advance.
int numdays = 15680;
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, 1);
cal.set(Calendar.YEAR, 1960);
cal.add(Calendar.DAY_OF_MONTH, numdays);
String strdate = null;
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-DD");
if (cal != null) {
strdate = sdf.format(cal.getTime());
}
System.out.println(strdate);
Month are 0-based, so you're setting your calendar to February, not January. This should fix the issue:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.MONTH, Calendar.JANUARY);
// ...
In addition to RC's point about starting the month correctly with Calendar.JANUARY, your simpledateformat is wrong.
SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd");
'DD' is day of year (so 340th day of the year is Dec 6). 'dd' is day of the month. See the doc for more detail. (Also note that 15680 is Dec 6 2002, not what you say in the question.)
You may actually want to use 'yy' also:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
as 'YYYY' is "Week Year", which in some cases may differ from yyyy (calendar year) near the end of the year. See the docs for more details.
I like to use JodaTime for date manipulation like this.
http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#plusDays-int-
int sasDate = 19725;
DateTime base = new DateTime(1960, 1, 1, 0, 0);
DateTime computed = base.plusDays(sasDate);
I have to parse "17-Jun" format date using Java.But the problem is when I try to parse "dd-MM" format using SimpleDateFormat it is returning as "Wed Jun 17 00:00:00 IST 1970".Is it possible to get current(2014) year instead of 1970.
My result:
17/JUNE/1970
Expected result:
17/JUNE/2014
Have a look at this..
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 17);
c.set(Calendar.MONTH, 5);
c.set(Calendar.YEAR, c.get(Calendar.YEAR));
Date date=new Date(c.getTimeInMillis());
SimpleDateFormat simpleDateformatter = new SimpleDateFormat("dd/mmm/yyyy");
String convertedDate = simpleDateformatter .format(date);
To get year you can just use
Calendar cal = Calendar.getInstance();
cal.get(Calendar.YEAR) will fetch you current year
Hope it helped... :)
Try this
Calendar c = Calendar.getInstance();
c.set(Calendar.DATE, 17);
c.set(Calendar.MONTH, 5);
c.set(Calendar.YEAR, c.get(Calendar.YEAR));
Date d=new Date(c.getTimeInMillis());
SimpleDateFormat formatter = new SimpleDateFormat("dd- mmm");
String conDate = formatter.format(d);
Do like this
Date date = new SimpleDateFormat("dd-MMM-yyyy").parse("17-Jun-"+ Calendar.getInstance().get(Calendar.YEAR));
You'll have to write a utility method, there isn't anything in SimpleDateFormat that will interpret a non-existant year as the current year. Something like this:
public static Date parseDate(String dateString) throws ParseException {
//determine current year
Calendar today = Calendar.getInstance();
int currentYear = today.get(Calendar.YEAR);
//parse input
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
Date parsed = format.parse(dateString);
// set current year on parsed value
Calendar cal = Calendar.getInstance();
cal.setTime(parsed);
cal.set(Calendar.YEAR, currentYear);
return cal.getTime();
}
Try this:
SimpleDateFormat dfDate = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date d = null;
try {
d = dfDate.parse("17-Jun-"+ Calendar.getInstance().get(Calendar.YEAR));
} catch (java.text.ParseException e) {
e.printStackTrace();
}
System.out.println(""+d );
your problem will be solved.
java.time
In Java 8 you can do something like:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("d-MMM");
MonthDay md = MonthDay.parse("17-Jun", dtf);
LocalDate d = LocalDate.now().with(md);
System.out.println(d.getDayOfMonth());
System.out.println(d.getMonthValue());
System.out.println(d.getYear());
I guess the simplest way is to do this:
DateFormat dateFormat = new SimpleDateFormat("yyyy/MMM/dd");
Date date = new Date();
System.out.println("Time is: " + dateFormat.format(date) );
This gives you exactly what you want. also see
http://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
Little late, but if you really don't want to use Calendar at all - as I gather from your comments to the correct answers above - (not recommended with the usage of deprecated methods, but still):
SimpleDateFormat format = new SimpleDateFormat("dd-MMM");
Date date = format.parse("17-JUN");
date.setYear(new Date().getYear());
System.out.println(date);
Output:
Tue Jun 17 00:00:00 IST 2014
All answers given here are more or less correct, but I notice that one detail aspect is still overlooked, namely if the combination of day and months fits to current year (february 29 problem). So I would suggest a strict parsing like following:
String ddMMM = "17-Jun";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
sdf.setLenient(false); // in order to check for "29-Feb"
TimeZone tz = TimeZone.getDefault(); // or change to your specific time zone
Date date =
sdf.parse(ddMMM + "-" + new GregorianCalendar(tz).get(Calendar.YEAR));
Try,
String s2 = "Wed Jun 17 00:00:00 1970";
SimpleDateFormat sdf1 = new SimpleDateFormat("E MMM dd hh:mm:ss yyyy");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MMM/yyyy");
try {
Date d1 = sdf1.parse(s2);
System.out.println(d1);
String s3 = sdf2.format(d1);
System.out.println("Before Changing :: "+s3);
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
cal.add(Calendar.YEAR, 2014-1970);
d1 = cal.getTime();
String s4 = sdf2.format(d1);
System.out.println("After Changing :: "+s4);
} catch (ParseException e) {
e.printStackTrace();
}
Output
Before Changing :: 17/Jun/1970
After Changing :: 17/Jun/2014
I'm trying to get the current time (HH:MM:SEC:MILLISEC) in an android app. I'm using this piece of code:
Calendar c = Calendar.getInstance();
int time_start = c.get(Calendar.MILLISECOND);
"Field number for get and set indicating the minute within the hour. E.g., at 10:04:15.250 PM the MILLI is 250."
I've looked through the other methods, but I couldn't find anything specifying it would output everything. Is there anyway I can get H:M:Sec:MilliSec? or do I just have to do something like
c.get(Calendar.HOUR).get(Calendar.MINUTE).get(Calendar.SECOND).get(Calendar.MILLISECOND).
You could try with SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
Like this perhaps:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSS");
String test = sdf.format(cal.getTime());
Log.e("TEST", test);
What about this?
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss:S");
String result = sdf.format(Calendar.getInstance().getTime());
System.out.println(result);
I would go the System.currentTimeMillis() or the new Date() way, and put these in a SimpleDateFormat, to get exactly the output you like