简体   繁体   中英

Java equivalent to C# $“{var}” formatting

So I am learning a bit of Java and I'm just curios if there is an equivalent to the string format with the $ sign like in C#. For example

string s = $"Date: {DateTime.Now}";
// s = Date: 5/27/2020 8:02:25 AM

Is this possible in Java? I find it more convenient than doing it with indexes.

Java provides a type-safe way of concatenating Strings.

Here is a demonstration using jshell:

> jshell

jshell> import java.time.*;

jshell> String s = ("Date: " + LocalDateTime.now());
s ==> "Date: 2020-05-27T09:49:10.476140"

jshell>

Here is a working example program that uses Date formatting:

// File name: Demo.java

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

public class Demo {
   public static void main(String[] args) {
      Format f = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");
      String s = ( "Date: " + f.format(new Date()) );
      System.out.println(s);
   }
}

Output:

> javac Demo.java

> java Demo
Date: 27/03/2020 10:03:02 am

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