You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.7KB

  1. #![allow(unused)]
  2. use chrono::{DateTime, Utc, NaiveDateTime};
  3. fn nanos(utc: DateTime<Utc>) -> u64 {
  4. (utc.timestamp() as u64) * 1_000_000_000_u64 + (utc.timestamp_subsec_nanos() as u64)
  5. }
  6. fn get_time() -> (i64, i32) {
  7. let mut tv = libc::timespec { tv_sec: 0, tv_nsec: 0 };
  8. unsafe { libc::clock_gettime(libc::CLOCK_REALTIME, &mut tv); }
  9. (tv.tv_sec as i64, tv.tv_nsec as i32)
  10. }
  11. fn timespec_to_utc(sec: i64, nsec: i32) -> DateTime<Utc> {
  12. let naive = NaiveDateTime::from_timestamp(sec, nsec as u32);
  13. DateTime::from_utc(naive, Utc)
  14. }
  15. fn timespec_to_nanos(sec: i64, nsec: i32) -> u64 {
  16. (sec as u64) * 1_000_000_000_u64 + (nsec as u64)
  17. }
  18. fn main() {
  19. let args: clap::ArgMatches = clap::App::new("utcnow")
  20. .author("Jonathan Strong <jonathan.strong@gmail.com>")
  21. .version(clap::crate_version!())
  22. .about("\ncurrent time in utc with non-cryptic interface.\n\n\
  23. for your own safety and well-being, local time functionality is not provided.\n\n\
  24. default output format is rfc3339 with trailing 'Z', e.g. '1999-12-31T23:59:59.999999999Z'")
  25. .help_message("help")
  26. .version_message("version")
  27. .arg(clap::Arg::with_name("unix")
  28. .help("display elapsed nanoseconds since 1970-01-01T00:00:00Z")
  29. .long("unix")
  30. .short("u")
  31. .required(false)
  32. .takes_value(false))
  33. .arg(clap::Arg::with_name("rfc2822")
  34. .help("display in rfc2822 format")
  35. .long("rfc2822")
  36. .short("r")
  37. .required(false)
  38. .takes_value(false))
  39. .arg(clap::Arg::with_name("seconds")
  40. .help("display unix timestamp in seconds, instead of default nanoseconds")
  41. .long("seconds")
  42. .short("s")
  43. .requires("unix")
  44. .required(false)
  45. .takes_value(false))
  46. .arg(clap::Arg::with_name("timespec")
  47. .help("display as <sec>,<nsec>")
  48. .long("timespec")
  49. .short("t")
  50. .required(false)
  51. .takes_value(false))
  52. .get_matches();
  53. let (sec, nsec) = get_time();
  54. if args.is_present("timespec") {
  55. println!("{},{}", sec, nsec);
  56. } else if args.is_present("unix") {
  57. if args.is_present("seconds") {
  58. println!("{}", sec);
  59. } else {
  60. println!("{}", timespec_to_nanos(sec, nsec));
  61. }
  62. } else if args.is_present("rfc2822") {
  63. println!("{}", timespec_to_utc(sec, nsec).to_rfc2822());
  64. } else {
  65. // Debug view is iso format / rfc3339 that we want
  66. // Display has spaces - no go
  67. // to_rfc3339 uses +00:00 instead of Z, which I don't like
  68. println!("{:?}", timespec_to_utc(sec, nsec));
  69. }
  70. }