[Dart] DateTime , int, double 연산

2020. 11. 4. 17:23Mobile/Flutter

Flutter 개발 시 DateTime, Number를 처리하기 위해 자주 사용되는 연산

DateTime

  1. DateTime 생성
    var now = DateTime.now(); //현재일자
    var then = new DateTime(2020, 11, 4, 15, 23, 58, 0, 0); //각 매개변수는 Optional Parameter
    
  2. DateFormat
    DateTime을 지정한 형식 문자열로 변환하려면 DateFormat Class를 사용해야합니다.
    (https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html 참고)
    /* 사전준비
       1) 먼저 pubspec.yaml의 dependencies에 아래 패키지 추가
       intl: ^0.16.0
    
       2) 다트파일에 import 추가
       import 'package:intl/intl.dart';  */
    
    //직접 Format 문자열 지정
    var now2 = DateTime.now();
    var format = 'yyyy-MM-dd (E) a HH:mm:ss';
    print(DateFormat(format).format(now2)); //출력: 2020-11-04 (Wed) PM 18:31:22
    
    //Locale에 따라 자동 Format
    var now = DateTime.now();
    print(DateFormat().format(now));  //출력: November 4, 2020 6:31:22 PM
    
  3. 추가/삭제
    //50일 추가
    var now = new DateTime.now();
    var added = now.add(new Duration(days: 50));
    
  4. 날짜 비교
    DateTime date1 = new DateTime(2020, 10, 31, 13, 21, 11);
    DateTime date2 = new DateTime(2020, 11, 4, 16, 18, 59);
    Duration diff = date1.difference(date2);
    
    print(' - isNagative: ${diff.isNegative} \r\n'
        + ' - inDays: ${diff.inDays} \r\n'
        + ' - inHours: ${diff.inHours} \r\n'
        + ' - inMinutes: ${diff.inMinutes} \r\n'
        + ' - inSeconds: ${diff.inSeconds} \r\n'
        + ' - inMilliseconds: ${diff.inMilliseconds} \r\n'
        + ' - inMicroseconds: ${diff.inMicroseconds}');
    
    /* 결과
      - isNagative: true
      - inDays: -4
      - inHours: -98
      - inMinutes: -5937
      - inSeconds: -356268
      - inMicroseconds: -356268000
      - inMicroseconds: -356268000000
    */
    

int, double 연산

  1. int, double 형변환
    //int -> double
    int from = 10;
    double to = from.toDouble();
    
    //double -> int
    double from = 10.1;
    int to = from.toInt(); //소수점 이하 절사(반올림 아님)
    
  2. 문자열 Parsing
    //실패 시 Exception
    int intVal = int.parse('10'); 
    double doubleVal = double.parse('10.1');
    
    //실패 시 null
    int intVal2 = int.tryParse('10');
    double doubleVal2 = double.tryParse('10.1');
    
  3. NumberFormat
    number 값을 지정한 형식 문자열로 변환하려면 NumberFormat Class를 사용해야합니다.
    (https://pub.dev/documentation/intl/latest/intl/NumberFormat-class.html 참고)
    /* 사전준비
       1) 먼저 pubspec.yaml의 dependencies에 아래 패키지 추가
       intl: ^0.16.0
    
       2) 다트파일에 import 추가
       import 'package:intl/intl.dart';  */
    
    //직접 Format 문자열 지정
    NumberFormat numberFormat = NumberFormat('#,###.##'); 
    print(numberFormat.format(11000)); //결과: 11,000
       
    //Locale에 따라 자동 Format
    NumberFormat numberFormat = NumberFormat.currency(symbol:'', decimalDigits: 2); //decimalDigits는 소수점 자리수
    print(numberFormat.format(10));  //결과: 10.00
  4. Currency 처리
    금액 등 정확도가 중요한 정보를 다룰 때 int Type만으로도 충분합니다. 하지만 소수점 이하를 다루기 위해 double을 사용해야 할 때는 주의할 점이 있습니다. double은 소수점 자리수가 길어질 수록 정확도가 떨어지기 때문입니다.
    double value = 1.0;
    var format = '#.00000000000000000';
    print(NumberFormat(format).format(value));
    //출력값: 1.00000000000020008 <- double은 소수점이 길어지면 정확도가 떨어짐
    
    따라서 부동소수점의 정확도가 중요한 경우 double 대신 decimal 등 외부 패키지를 사용해야 합니다.
    (https://pub.dev/packages/decimal 참고)
    /* 사전준비
       1) 먼저 pubspec.yaml의 dependencies에 아래 패키지 추가
       decimal: ^0.3.0
    
       2) 다트파일에 import 추가
       import 'package:decimal/decimal.dart';  */
    
    //Decimal 값 생성
    Decimal d1 = new Decimal.fromInt(1000);
    Decimal d2 = Decimal.parse('1.9000000000000000000000001');
    Decimal d3 = d1 + d2; //기본적인 연산 지원
    
    //형변환
    int intVal = d3.toInt();
    double dblVal = d3.toDouble();
    
    //문자열 변환
    String strVal = d3.toString(); //결과:1001.9000000000000000000000001
    //=> Locale과 관계없이 항상 0.###... 포멧으로 출력됨

References