DateTimePicker.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. using UnityEngine.UI;
  6. /// <summary>
  7. /// Дата в выпадающем списке
  8. /// </summary>
  9. public class DateTimePicker : MonoBehaviour
  10. {
  11. public Dropdown Day;
  12. public Dropdown Month;
  13. public Dropdown Year;
  14. public DateTime Date {
  15. get {
  16. var date = new DateTime(int.Parse(Year.options[Year.value].text), int.Parse(Month.options[Month.value].text), int.Parse(Day.options[Day.value].text));
  17. return date; }
  18. set {
  19. Days();
  20. //Year.value = Date.Year.;
  21. Month.value = Date.Month - 1;
  22. Day.value = Date.Day - 1;
  23. oldYear = Year.value;
  24. oldMonth = Month.value;
  25. }
  26. }
  27. int oldYear = -1;
  28. int oldMonth = -1;
  29. // Start is called before the first frame update
  30. void Start()
  31. {
  32. DateNow();
  33. }
  34. // Update is called once per frame
  35. void Update()
  36. {
  37. if (oldYear == -1 || oldMonth == -1)
  38. DateNow();
  39. if (oldYear != Year.value || oldMonth != Month.value)
  40. {
  41. Days();
  42. oldYear = Year.value;
  43. oldMonth = Month.value;
  44. }
  45. }
  46. void Days()
  47. {
  48. Day.options.Clear();
  49. var year = int.Parse(Year.options[Year.value].text);
  50. var month = int.Parse(Month.options[Month.value].text);
  51. var days = DateTime.DaysInMonth(year, month);
  52. for (int d = 1; d <= days; d++)
  53. Day.options.Add(new Dropdown.OptionData($"{d}"));
  54. Day.value = 0;
  55. }
  56. void DateNow()
  57. {
  58. for (var y = 2020; y <= DateTime.Now.Year; y++)
  59. Year.options.Add(new Dropdown.OptionData($"{y}"));
  60. for (var m = 1; m <= 12; m++)
  61. Month.options.Add(new Dropdown.OptionData($"{m}"));
  62. Year.value = Year.options.Count - 1;
  63. Month.value = DateTime.Now.Month - 1;
  64. oldYear = Year.value;
  65. oldMonth = Month.value;
  66. Days();
  67. Day.value = DateTime.Now.Day - 1;
  68. }
  69. }