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
Typically, you get a TimeZone using getDefault which creates a TimeZone based on the time zone where the program is running. For example, for a program running in Japan, getDefault creates a TimeZone object based on Japanese Standard Time. Hours must be between 0 to 23 and Minutes must be between 00 to 59.
If the specified string doesn't match the syntax, "GMT" is used. For example, TimeZone. getTimeZone("GMT-8"). getID() returns "GMT-08:00".
Call TimeZone. getAvailableIDs() to get the list of known timezones for your system. This permission is only allowed for system apps. on android api 26 and 27 receive this error: setTimeZone: Neither user 10087 nor current process has android.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With