Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

salesforce - String Formatting in Apex

I have to format string day='11/22/1999' into '2020-11-26T00:00:00-05:00' this String format with default time value as 0 in apex. please let me know if anyone worked on this.


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

1 Reply

0 votes
by (71.8m points)

This will output in the running user's time zone.

System.debug(formatDate('11/22/1999')); //1999-11-22T00:00:00-05:00

String formatDate(String dateString) {
    Date d = Date.parse(dateString);
    Datetime dt = Datetime.newInstance(d.year(), d.month(), d.day(), 0, 0, 0);
    return dt.format('yyyy-MM-dd'T'HH:mm:ssXXX');
}
  1. Date.parse() will create a Date from your string.
  2. With that date, you can create a Datetime using Datetime.newInstance() while also zeroing out the time for your locale.
  3. Use Datetime.format() to generate the desired formatted string. (The penultimate formatting example is a very close match to what you want.)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...