简体   繁体   中英

How can I get the current time in particular format, for a particular zone?

I want to get the current DateTime in a zone of my choice and in a particular format (eg HH-MM-SS, MM-DD-YY, MoMo-DD-YY-HH-MM-SS etc). How can I do this, using JodaTime?

Given that you've already seen the user guide (which includes sections on time zones and formatting ), it's not really clear where your confusion is. Some sample code to get you going:

DateTimeZone zone = DateTimeZone.forID("Europe/London");
DateTime currentTimeInLondon = new DateTime(zone);
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss, MM-dd-yyyy");
String text = formatter.print(currentTimeInLondon); // e.g. 08:24:54, 09-26-2012

It would be worth you taking some time to analyze why you couldn't get to this code yourself, given the information in the user guide. Being able to work out how to use APIs is a very important skill as a software engineer - you mustn't expect to be spoonfed code all the time.

Use following code to get time according to particular zone with format.

    Locale locale = Locale.FRENCH;

    // Format with a custom format
    DateFormat formatter = new SimpleDateFormat("E, dd MMM yyyy", locale);
    String s = formatter.format(new Date());
    // mar., 29 sept. 2012

    // Format with a default format
    s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
    // 29 sept. 2012

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM