Konwertuj Javę.util.Date to String

Chcę przekonwertować obiekt java.util.Date Na String w Javie.

Format to 2010-05-30 22:15:52

Author: Vadzim, 2011-04-16

16 answers

W języku Java Konwertuj datę na ciąg znaków za pomocą ciągu w formacie:

// Create an instance of SimpleDateFormat used for formatting 
// the string representation of date (month/day/year)
DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");

// Get the date today using Calendar object.
Date today = Calendar.getInstance().getTime();        
// Using DateFormat format method we can create a string 
// representation of a date with the defined format.
String reportDate = df.format(today);

// Print what date is today!
System.out.println("Report Date: " + reportDate);

Z http://www.kodejava.org/examples/86.html

 696
Author: alibenmessaoud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-22 22:16:51
Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
 198
Author: Charlie Salts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-16 01:02:29

Commons-lang DateFormat = YYYY jest pełna gadżetów (jeśli masz commons-lang w swojej ścieżce klasowej)

//Formats a date/time into a specific pattern
 DateFormatUtils.format(yourDate, "yyyy-MM-dd HH:mm:SS");
 56
Author: webpat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-05-10 10:25:51

Tl; dr

myUtilDate.toInstant()  // Convert `java.util.Date` to `Instant`.
          .atOffset( ZoneOffset.UTC )  // Transform `Instant` to `OffsetDateTime`.
          .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a String.
          .replace( "T" , " " )  // Put a SPACE in the middle.

2014-11-14 14:05:09

Java.czas

Nowoczesny sposób jest z java.klasy Czasu, które teraz zastępują kłopotliwe stare klasy daty-czasu.

Najpierw przekonwertuj swoje java.util.Date na Instant. Na Instant Klasa reprezentuje moment na osi czasu w UTC z rozdzielczością nanosekund (do dziewięciu (9) cyfr ułamka dziesiętnego).

Konwersje do / Z Javy.time are wykonywane przez nowe metody dodane do starych klas.

Instant instant = myUtilDate.toInstant();

Zarówno twoje java.util.Date jak i java.time.Instantsą w UTC . Jeśli chcesz zobaczyć datę i godzinę jako UTC, niech tak będzie. Wywołanie toString, aby wygenerować ciąg znaków w standardowym formacie ISO 8601 .

String output = instant.toString();  

2014-11-14T14: 05: 09Z

W przypadku innych formatów musisz przekształcić swój Instant w bardziej elastyczny OffsetDateTime.

OffsetDateTime odt = instant.atOffset( ZoneOffset.UTC );

Odt.toString(): 2014-11-14T14:05:09+00:00

Aby uzyskać ciąg znaków w pożądanym formacie, podaj DateTimeFormatter. Możesz określić niestandardowy format. Ale użyłbym jednego z predefiniowanych formaterów (ISO_LOCAL_DATE_TIME), i zastąp T w jego wyjściu spacją.

String output = odt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " );

2014-11-14 14:05:09

Przy okazji nie polecam tego rodzaju formatu, w którym celowo traciszoffset-from-UTC lub informacje o strefie czasowej. Tworzy niejednoznaczność co do znaczenie wartości date-time tego łańcucha.

Uważaj również na utratę danych, ponieważ każda ułamkowa sekunda jest ignorowana (skutecznie obcinana) w reprezentacji ciągu znaków wartości data-czas.

Aby zobaczyć ten sam moment przez obiektyw jakiegoś konkretnego regionu zegar ścienny , zastosuj ZoneId, aby uzyskać ZonedDateTime.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );

Zdt.toString (): 2014-11-14t14: 05: 09-05: 00[Ameryka/Montreal]

Aby wygenerować sformatowany Łańcuch, wykonaj to samo co powyżej, ale zastąp odt przez zdt.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
                   .replace( "T" , " " );

2014-11-14 14:05:09

Jeśli wykonasz ten kod bardzo wiele razy, możesz chcieć być nieco bardziej wydajny i uniknąć wywołania String::replace. Rezygnacja z połączenia również skraca kod. W razie potrzeby określ swój własny wzór formatowania w swoim obiekcie DateTimeFormatter. Buforuj tę instancję jako stałą lub element do ponownego użycia.

DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuuu-MM-dd HH:mm:ss" );  // Data-loss: Dropping any fractional second.

Zastosuj ten formater przekazując przykład.

String output = zdt.format( f );

O Javie.czas

Java.Framework time jest wbudowany w Javę 8 i nowszą. Klasy te zastępują kłopotliwe stare klasy datujące, takie jak java.util.Date, .Calendar, & java.text.SimpleDateFormat.

Projekt Joda-Time{ [ 41]}, obecnie w trybie konserwacji , radzi migrację do Javy.czas.

Aby dowiedzieć się więcej, zapoznaj się z samouczkiem Oracle . I wyszukaj przepełnienie stosu dla wielu przykładów i wyjaśnienia.

Większość Javy.funkcja czasu jest z powrotem przeniesiona do Java 6 & 7 w ThreeTen-Backport i dalej dostosowana do Android w ThreeTenABP (zobacz jak używać...).

Projekt ThreeTen-Extra rozszerza Javę.czas z dodatkowymi zajęciami. Ten projekt jest poligonem dla potencjalnych przyszłych dodatków do Javy.czas.

 18
Author: Basil Bourque,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:18:20

Altenative one-liners in plain-old java:

String.format("The date: %tY-%tm-%td", date, date, date);

String.format("The date: %1$tY-%1$tm-%1$td", date);

String.format("Time with tz: %tY-%<tm-%<td %<tH:%<tM:%<tS.%<tL%<tz", date);

String.format("The date and time in ISO format: %tF %<tT", date);

Używa Formatera i względnego indeksowania zamiast SimpleDateFormat, który jest nie bezpieczny dla wątków , btw.

Nieco bardziej powtarzalne, ale wymaga tylko jednego stwierdzenia. W niektórych przypadkach może to być przydatne.

 13
Author: Vadzim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-20 12:42:43

Dlaczego nie użyjesz Jody (org.joda.czas.DateTime)? To w zasadzie jednoliniowy.

Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");

// output: 2014-11-14 14:05:09
 9
Author: dbow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-15 00:14:47

Wygląda na to, że szukasz SimpleDateFormat .

Format: RRRR-MM-dd kk: mm: ss

 7
Author: pickypg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-16 01:01:54
public static String formateDate(String dateString) {
    Date date;
    String formattedDate = "";
    try {
        date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss",Locale.getDefault()).parse(dateString);
        formattedDate = new SimpleDateFormat("dd/MM/yyyy",Locale.getDefault()).format(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return formattedDate;
}
 4
Author: Ashish Tiwari,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-31 06:31:29

Najprostszy sposób użycia jest następujący:

currentISODate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss", "2013-04-14T16:11:48.000");

Gdzie "yyyy-MM-dd' HH:mm:ss " jest formatem daty odczytu

Wyjście: Nie Kwi 14 16:11:48 EEST 2013

Uwagi: HH vs hh - HH odnosi się do formatu czasu 24h - HH odnosi się do formatu czasu 12h

 4
Author: Rami Sharaiyri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-22 12:24:27

Jeśli potrzebujesz tylko czasu od daty, możesz po prostu użyć funkcji String.

Date test = new Date();
String dayString = test.toString();
String timeString = dayString.substring( 11 , 19 );

Spowoduje to automatyczne przecięcie części czasowej łańcucha i zapisanie go wewnątrz timeString.

 4
Author: funaquarius24,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-07 08:03:02

Oto przykłady użycia nowego Java 8 Time API do formatowania legacy java.util.Date:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z")
        .withZone(ZoneOffset.UTC);
    String utcFormatted = formatter.format(date.toInstant()); 

    ZonedDateTime utcDatetime = date.toInstant().atZone(ZoneOffset.UTC);
    String utcFormatted2 = utcDatetime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS Z"));
    // gives the same as above

    ZonedDateTime localDatetime = date.toInstant().atZone(ZoneId.systemDefault());
    String localFormatted = localDatetime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
    // 2011-12-03T10:15:30+01:00[Europe/Paris]

    String nowFormatted = LocalDateTime.now().toString(); // 2007-12-03T10:15:30.123

To miłe, że DateTimeFormatter może być efektywnie buforowany, ponieważ jest bezpieczny dla wątków(w przeciwieństwie do SimpleDateFormat).

Lista predefiniowanych fomatterów i odniesienia do notacji wzorcowej .

Napisy:

Jak parsować / formatować daty Za pomocą LocalDateTime? (Java 8)

Java8 java.util.Konwersja daty do Javy.czas.ZonedDateTime

Format Instant to String

Jaka jest różnica między java 8 ZonedDateTime i OffsetDateTime?

 3
Author: Vadzim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:33

Spróbuj tego,

import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Date
{
    public static void main(String[] args) 
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = "2013-05-14 17:07:21";
        try
        {
           java.util.Date dt = sdf.parse(strDate);         
           System.out.println(sdf.format(dt));
        }
        catch (ParseException pe)
        {
            pe.printStackTrace();
        }
    }
}

Wyjście:

2013-05-14 17:07:21

Aby dowiedzieć się więcej o formatowaniu daty i czasu w języku java, zapoznaj się z poniższymi linkami

Centrum Pomocy Oracle

Przykład daty i czasu w języku java

 2
Author: Shiva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-06 11:38:52

In single shot;)

Aby uzyskać datę

String date = new SimpleDateFormat("yyyy-MM-dd",   Locale.getDefault()).format(new Date());

Aby uzyskać czas

String time = new SimpleDateFormat("hh:mm", Locale.getDefault()).format(new Date());

Aby uzyskać datę i godzinę

String dateTime = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefaut()).format(new Date());

Happy coding:)

 2
Author: S.D.N Chanaka Fernando,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-03 20:43:11
public static void main(String[] args) 
{
    Date d = new Date();
    SimpleDateFormat form = new SimpleDateFormat("dd-mm-yyyy hh:mm:ss");
    System.out.println(form.format(d));
    String str = form.format(d); // or if you want to save it in String str
    System.out.println(str); // and print after that
}
 1
Author: Artanis,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-03-25 21:41:22

Spróbujmy tego

public static void main(String args[]) {

    Calendar cal = GregorianCalendar.getInstance();
    Date today = cal.getTime();
    DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {           
        String str7 = df7.format(today);
        System.out.println("String in yyyy-MM-dd format is: " + str7);          
    } catch (Exception ex) {
      ex.printStackTrace();
    }
}

Lub funkcja użytkowa

public String convertDateToString(Date date, String format) {
    String dateStr = null;
    DateFormat df = new SimpleDateFormat(format);

    try {
        dateStr = df.format(date);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    return dateStr;
}

Z Konwertuj datę na ciąg znaków w Javie

 1
Author: David Pham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-26 16:25:09
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date = "2010-05-30 22:15:52";
    java.util.Date formatedDate = sdf.parse(date); // returns a String when it is parsed
    System.out.println(sdf.format(formatedDate)); // the use of format function returns a String
 1
Author: Dulith De Costa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-23 14:52:16