Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

java - Getting device's local timezone

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...