2010-06-14 02:21:49+0400 or 2010-06-14 02:21:49-0400
is there a way to convert this string to the date according to the local machine time zone with format 2010-06-14 02:21 AM
Adding to what #org.life.java and #Erica said, here's what you should do
String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);
System.out.println(newDateStr);
Then newDateStr will be your new date formatted string.
UPDATE #xydev, the example I gave you works, see the full source code below:
/**
*
*/
package testcases;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* #author The Elite Gentleman
*
*/
public class Test {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);
System.out.println(newDateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Output: 2010-06-14 08:21:49 AM
Using SimpleDateFormat
String string1 = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);
Note: I am not sure the same class is available in andriod.
You can do all sorts of fancy formatting and localisation of dates using the DateFormat class. There's very good, complete documentation at the start of the API page here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html
Most regular cases can be handled with the built in SimpleDateFormat object. Its details are here:
http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
The SimpleDateFormat output pattern string for the example you have above would be:
yyyy-MM-dd hh:mm a
Be careful that if you are running on the emulator your timezone is always GMT. I just spent 2 hours in trying to understand why my application does not give me the right time (the one my computer displays) until I realized it is because of the emulator.
To check you are running on the emulator use
if (Build.PRODUCT.contains("sdk")){
// your code here for example if curtime has the emulator time
// since midnight in milliseconds then
curtime += 2 * 60 * 60 * 1000; // to add 2 hours from GMT
}
Related
I just need sample code block or suggestion to convert the following date string to utc time in format yyyy-MM-dd HH:mm:ss?
sample date string:11/23/2017 09:44am
there are similar questions like this but my test data is with am/pm.So pls dont consider this as duplicate
You could use the Java 8 time package:
String input = "11/23/2017 09:44am";
String format = "MM/dd/yyyy hh:mma";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(format);
LocalDateTime date = LocalDateTime.parse(input, formatter);
System.out.printf("%s%n", date);
But the problem is: this throws a DateTimeParseException, because of the lowercase 'am'.
I looked up in the docs, but I couldn't see a standard way to parse lowercase 'am' or 'pm' as as meridiem designator1. You'll end up manually replacing them:
input = input.replace("AM", "am").replace("PM","pm");
As mentioned by #OleVV in the comments, you can use a DateTimeFormatterBuilder and specify that the parsing should be case-insensitive:
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(format)
.toFormatter();
Then you can use this formatter as argument to the LocalDateTime.parse method.
Another answer of the aforementioned post provides a solution where you can override the AM/PM symbols with the lowercase variants.
1 Interestingly, the SimpleDateFormat does support the parsing of lowercase am/pm.
The sample code below should do the conversion correctly.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateConversion {
public static void main(String[] argv) {
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mma");
SimpleDateFormat OutputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String sampleDateString = "11/23/2017 09:44am";
try {
Date convertDate = formatter.parse(sampleDateString);
System.out.println(OutputFormatter.format(convertDate));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
This is to declare the date string to be parsed.
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy hh:mma");
and the output date as well
SimpleDateFormat OutputFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
At first you need to create a SimpleDateFormat with the proper pattern. This class helps you to parse your string to java.util.Date (more info here):
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma");
If your original string-date is in a special timezone then you need to instruct the parser to use this timezone:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma", Locale.ENGLISH);
Then you need to parse the string to date:
Date d = sdf.parse("11/23/2017 09:44am");
Finnaly you have to convert the timezoned date to UTC.
Please find bellow the full code snippet:
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy hh:mma", Locale.ENGLISH);
Date d = sdf.parse("11/23/2017 09:44am");
System.out.println(toUtcZonedDateTime(d));
}
public static ZonedDateTime toUtcZonedDateTime(final Date date) {
if (date == null) {
return null;
}
final ZoneId utcZone = ZoneOffset.UTC;
return ZonedDateTime.ofInstant(date.toInstant(), utcZone);
}
Output:
2017-11-23T08:44Z
SimpleDateFormat's javadoc lists all the options, including "a" for am/pm marker.
In you case, you need:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssa")
I have table with data of date.
This is how I calcaulted the date
DateFormat dateFormat = getFormat();
date = dateFormat.parse((String) value).getTime();
if(date != null) {
cell.setValue(dateFormat.format(date));
tableViewer.update(element, null);
}
public static DateFormat getFormat() {
String systemLocale = System.getProperty("user.language"); //$NON-NLS-1$
Locale locale = new Locale(systemLocale);
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);
return dateFormat;
}
The date is exist in the screen in format Month(name of the month) date, year
for example Apr 26,2014.
Now I want to get the value of the cell and to get to format of 'yyyy-mm-dd'
The value of the date is Apr 26,2014.
How I can get the result of 2014-04-26 ? also I think that the value in the UI could change according to the localization of the user
I tried
DateFormat dateFormat = getFormat();
Date parse = dateFormat.parse((String) key);
but then all the get method are deprecated and also I didn't get right result for getYear
I am not expert in the date maybe I miss something
Try this:
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class CustomFormattedDate {
public static void main(String[] args) {
Date date = new Date();
// if you use DD for Daypattern, you'll get the day of the year, e.g. 119 for the
// 29th April 2014, if you want 29, the day of the month, use dd
SimpleDateFormat df = new SimpleDateFormat("YYYY-dd-MMM", new Locale(System.getProperty("user.language")));
System.out.println(df.format(date));
System.out.println(getDateFormat().format(date));
}
}
Output
2014-29-Apr
When running through the below code I am getting an UNPARSABLE DATE EXCEPTION.
How do I fix this?
package dateWork;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateCreation {
/**
* #param args
*/
public static void main(String[] args) {
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
Date startDate=null;
String newDateString = null;
try
{
startDate = df.parse(startDateString);
newDateString = df.format(startDate);
System.out.println(startDate);
} catch (ParseException e)
{
e.printStackTrace();
}
}
}
You used wrong dateformat for month, also you should use the same delimiter as in your date.
If you date string is of format "2013/01/03"
use the same delimiter / for the pattern "yyyy/MM/dd"
If your date string is of format "2013-01-03"
use the same delimiter '-' in your pattern "yyyy-MM-dd"
DateFormat df = new SimpleDateFormat("yyyy/mm/dd");
should be
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
From SimpleDateFormat Doc
MM---> month in an year
mm---> minutes in hour
MM instead of mm
- instead of /
ie yyyy-MM-dd as you are using - in date string
String startDateString = "2013-03-26";
DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
you are using different pattern than what you are parsing.
either initialize this as DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
or this as String startDateString = "2013/03/26";
also look this article
pass same format string in constructor of SimpleDateFormat("yyyy-mm-dd")
as your string date is "2013-03-26"
if your date is "2013/03/26" use
SimpleDateFormat("yyyy/mm/dd")
What is the easiest way to do this in Java? Ideally I will be using Unix time in milliseconds as input and the function will output a String like
November 7th, 2011 at 5:00 PM
SimpleDateFormat sdf = new SimpleDateFormat("MMMM d, yyyy 'at' h:mm a");
String date = sdf.format(myTimestamp);
I wanted to convert my unix_timestamps like 1372493313 to human readable format like Jun 29 4:08.
The above answered helped me for my Android app code. A little difference was that on Android it recommends to use locale settings as well, and my original unix_timestamp was in seconds, not milliseconds, and Eclipse wanted to add try/catch block or throw exception. So my working code has to be modified a bit like this:
/**
*
* #param unix_timestamp
* #return
* #throws ParseException
*/
private String unixToDate(String unix_timestamp) throws ParseException {
long timestamp = Long.parseLong(unix_timestamp) * 1000;
SimpleDateFormat sdf = new SimpleDateFormat("MMM d H:mm", Locale.CANADA);
String date = sdf.format(timestamp);
return date.toString();
}
And here is the calling code:
String formatted_timestamp;
try {
formatted_timestamp = unixToDate(unix_timestamp); // timestamp in seconds
} catch (ParseException e) {
e.printStackTrace();
}
java.util.Date date = new java.util.Date((long) time * 1000L);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
I have a date in(string) in dd-mon-yyyy format and I want to compare this date with system date.
eg.
I have 12-OCT-2010
and I want to compere this with system date in same format
You can use the SystemDateFormat class to parse your String, for example
final DateFormat fmt = new SimpleDateFormat("dd-MMM-yyyy");
final Date input = fmt.parse("12-OCT-2010");
if (input.before(new Date()) {
// do something
}
Note that SimpleDateFormat is not threadsafe, so needs to be wrapped in a ThreadLocal if you have more than one thread accessing your code.
You may also be interested in Joda, which provides a better date API
Use SimpleDateFormat http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
String d = "12-OCT-2010";
try {
Date formatted = f.parse(d);
Date sysDate = new Date();
System.out.println(formatted);
System.out.println(sysDate);
if(formatted.before(sysDate)){
System.out.println("Formatted Date is older");
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I would recommend using Joda Time. You can parse that String into a LocalDate object very simply, and then construct another LocalDate from the system clock. You can then compare these dates.
Using simpledateformat -
String df = "dd-MMM-yyyy";
SimpleDateFormat sdf = new SimpleDateFormat(df);
Calendar cal = Calendar.getInstance();
/* system date */
String systemdate = sdf.format(cal.getTime());
/* the date you want to compare in string format */
String yourdate = "12-Oct-2010";
Date ydate = null;
try {
ydate = sdf.parse(yourdate);
} catch (ParseException e) {
e.printStackTrace();
}
yourdate = sdf.format(ydate);
System.out.println(systemdate.equals(yourdate) ? "true" : "false");