BsonDateTimeSerializer.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. namespace MongoDB.Bson.Serialization.Serializers
  16. {
  17. /// <summary>
  18. /// Represents a serializer for BsonDateTimes.
  19. /// </summary>
  20. public class BsonDateTimeSerializer : BsonValueSerializerBase<BsonDateTime>
  21. {
  22. // private static fields
  23. private static BsonDateTimeSerializer __instance = new BsonDateTimeSerializer();
  24. // constructors
  25. /// <summary>
  26. /// Initializes a new instance of the BsonDateTimeSerializer class.
  27. /// </summary>
  28. public BsonDateTimeSerializer()
  29. : base(BsonType.DateTime)
  30. {
  31. }
  32. // public static properties
  33. /// <summary>
  34. /// Gets an instance of the BsonDateTimeSerializer class.
  35. /// </summary>
  36. public static BsonDateTimeSerializer Instance
  37. {
  38. get { return __instance; }
  39. }
  40. // protected methods
  41. /// <summary>
  42. /// Deserializes a value.
  43. /// </summary>
  44. /// <param name="context">The deserialization context.</param>
  45. /// <param name="args">The deserialization args.</param>
  46. /// <returns>A deserialized value.</returns>
  47. protected override BsonDateTime DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
  48. {
  49. var bsonReader = context.Reader;
  50. return new BsonDateTime(bsonReader.ReadDateTime());
  51. }
  52. /// <summary>
  53. /// Serializes a value.
  54. /// </summary>
  55. /// <param name="context">The serialization context.</param>
  56. /// <param name="args">The serialization args.</param>
  57. /// <param name="value">The object.</param>
  58. protected override void SerializeValue(BsonSerializationContext context, BsonSerializationArgs args, BsonDateTime value)
  59. {
  60. var bsonWriter = context.Writer;
  61. bsonWriter.WriteDateTime(value.MillisecondsSinceEpoch);
  62. }
  63. }
  64. }