0

How can I format an integer such as "20190331" to output as "2019-03-31" without firstly converting it to a date and without splitting it using substring. The date is stored as an integer in SQLite (SQFlite). I would like to do it in 1 line such as (pseudo code) Note: integer :

(pseudo) String sDate = fmt("####'-'##'-'##", map["DueDate"]); 

I know that I could do it such as :

String sDate = map["DueDate"].toString();
sDate = sDate.substring(0,4)+'-'+sDate.substring(4,6)+'-'+sDate.substring(6,8);

That however is two lines of code, and Visual Studio Code turns it into 8 lines when formatted and I like to keep my code compact.

Brian Oh
  • 9,604
  • 12
  • 49
  • 68

1 Answers1

1

Write a function called fmt and call it as in your pseudo code.

String fmt(String f, int i) {
  StringBuffer sb = StringBuffer();
  RuneIterator format = RuneIterator(f);
  RuneIterator input = RuneIterator(i.toString());
  while (format.moveNext()) {
    var currentAsString = format.currentAsString;
    if (currentAsString == '#') {
      input.moveNext();
      sb.write(input.currentAsString);
    } else {
      sb.write(currentAsString);
    }
  }
  return sb.toString();
}

one line:

  print(fmt('####-##-##', 20190331));
Richard Heap
  • 48,344
  • 9
  • 130
  • 112
  • Thanks Richard. I should have looked a few hours ago, because I wrote my own more generalized function. I'll try yours though, and if it works I'll give it a tick and I can probably learn from yours. – Brian Oh Apr 01 '19 at 06:48