Domanda

Come posso convertire

Wed Apr 27 17:53:48 PKT 2011

a

Apr 27, 2011 5:53:48 PM.
È stato utile?

Soluzione

new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a.").format(yourDate);

Altri suggerimenti

È possibile utilizzare SimpleDateFormat o JodaTime di parser.

Tuttavia potrebbe essere abbastanza semplice da scrivere il proprio parser String come si sta solo riordinando campi.

È possibile farlo utilizzando un mix di JDK e Joda tempo :

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

public class SO5804637 {

    public static void main(String[] args) throws ParseException {
        DateFormat df = 
            new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
        Date d = df.parse("Wed Apr 27 17:53:48 PKT 2011");
        DateTimeFormatter dtf = 
            DateTimeFormat.forPattern("MMM dd, yyyy hh:mm:ss a");
        DateTime dt = new DateTime(d);
        System.out.println(dt.toString(dtf));
    }

}

. Nota: ho incluso le dichiarazioni import per far capire quali classi che sto usando

SimpleDateFormat sdf = new SimpleDateFormat ("MMM dd, yyyy hh:mm:ss a");

String str = sdf.format(date)

Bene, è possibile convertire in questo modo,

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class StringToDateDemo
{
   public static void main(String[] args) throws ParseException  
   {
      String strDate = "Apr 27, 2011 5:53:48 pm";
      SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy hh:mm:ss a");
      Date dt = sdf.parse(strDate);
      System.out.println(dt);
   }
}

Output:

Apr 27, 2011 5:53:48 PM

Riferimento:

https://docs.oracle.com /javase/8/docs/api/java/text/SimpleDateFormat.html

https://www.flowerbrackets.com/java-convert- string-to-date /

È possibile utilizzare SimpleDateFormat per convertire una stringa in una data in una presentazione data. Un esempio di utilizzo SimpleDateFormat può essere trovato nel luogo seguente: http://www.kodejava.org /examples/19.html

new java.text.SimpleDateFormat("MMM d, yyyy h:mm:ss a").format(date);

Ho notato l'output desiderato avuto l'ora del giorno non preceduto dal 0 in modo che la stringa di formato che vi serve deve avere solo un singolo 'h'. Sto indovinando si desidera che il giorno del mese per avere un comportamento simile in modo che il modello contiene un solo 'd' troppo.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top