Advertisement
Guest User

Untitled

a guest
Aug 2nd, 2015
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.40 KB | None | 0 0
  1. package moment
  2.  
  3. import (
  4. "strconv"
  5. "strings"
  6. )
  7.  
  8. // Parse parses a duration string and returns number of nano seconds
  9. // durations can have 'ns', 'us', 'ms', 'min', 'hour', 'day' as suffix
  10. func Parse(str string) (ns int64, err error) {
  11. switch {
  12. case strings.HasSuffix(str, "ns"):
  13. nstr := str[:len(str)-2]
  14. return strconv.ParseInt(nstr, 10, 0)
  15. case strings.HasSuffix(str, "us"):
  16. nstr := str[:len(str)-2]
  17. if ns, err = strconv.ParseInt(nstr, 10, 0); err != nil {
  18. return 0, err
  19. }
  20.  
  21. return ns * 1e3, nil
  22. case strings.HasSuffix(str, "ms"):
  23. nstr := str[:len(str)-2]
  24. if ns, err = strconv.ParseInt(nstr, 10, 0); err != nil {
  25. return 0, err
  26. }
  27.  
  28. return ns * 1e6, nil
  29. case strings.HasSuffix(str, "s"):
  30. nstr := str[:len(str)-1]
  31. if ns, err = strconv.ParseInt(nstr, 10, 0); err != nil {
  32. return 0, err
  33. }
  34.  
  35. return ns * 1e9, nil
  36. case strings.HasSuffix(str, "min"):
  37. nstr := str[:len(str)-3]
  38. if ns, err = strconv.ParseInt(nstr, 10, 0); err != nil {
  39. return 0, err
  40. }
  41.  
  42. return ns * 1e9 * 60, nil
  43. case strings.HasSuffix(str, "hour"):
  44. nstr := str[:len(str)-4]
  45. if ns, err = strconv.ParseInt(nstr, 10, 0); err != nil {
  46. return 0, err
  47. }
  48.  
  49. return ns * 1e9 * 60 * 60, nil
  50. case strings.HasSuffix(str, "day"):
  51. nstr := str[:len(str)-3]
  52. if ns, err = strconv.ParseInt(nstr, 10, 0); err != nil {
  53. return 0, err
  54. }
  55.  
  56. return ns * 1e9 * 60 * 60 * 24, nil
  57. default:
  58. return strconv.ParseInt(str, 10, 0)
  59. }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement