好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Mongodb 如何将时间戳转换为年月日日期

Mongodb将时间戳转换为年月日日期

使用dateToString 方法进行转换 并且通过format指定转换日期格式

?

1

2

3

4

5

6

7

8

        Integer userId=aaa;

        GroupOperation groupOperation = Aggregation.group( "day" ).sum( "money" ).as( "todayIncome" ).count().as( "todayPayCount" );

        Aggregation aggregation = Aggregation.newAggregation(

                Aggregation.match(Criteria.where( "userId" ).is(userId)),

                project( "userId" , "money" ).andExpression( "{$dateToString: {date: { $add: {'$createTime', [0]} }, format: '%Y%m%d'}}" , new Date( 28800000 )).as( "day" ),

                groupOperation,

                sort(Sort.Direction.ASC, "_id" )

        );

注意:

1.必须使用 $dateToString: {date: { $add: 通过求和进行date数据转换 如果去掉后面的会报解析错误

org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 16006 (Location16006): 'can't convert from BSON type long to Date' on server localhost:50000. The full response is {"ok": 0.0, "errmsg": "can't convert from BSON type long to Date", "code": 16006, "codeName": "Location16006"}; nested exception is com.mongodb.MongoCommandException: Command failed with error 16006 (Location16006): 'can't convert from BSON type long to Date' on server localhost:50000. The full response is {"ok": 0.0, "errmsg": "can't convert from BSON type long to Date", "code": 16006, "codeName": "Location16006"}

2.必须增加 new Date(28800000) 的时间 原因是增加了8个时区的偏移量

MongoDB中的日期查询的坑

在熟悉monggoDB的时候遇到了时间查询的问题代码如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

import java.text.SimpleDateFormat;

import java.util.ArrayList;

import java.util.List;

 

import com.mongodb.BasicDBObject;

import com.mongodb.DB;

import com.mongodb.DBCollection;

import com.mongodb.DBCursor;

import com.mongodb.DBObject;

import com.mongodb.MongoClient;

import com.mongodb.ServerAddress;

 

/**

  * mongo 数据库直连测试

  * @author fuhao

  *

  */

public class MongDBTest {

     public static void main(String[] args) throws Exception {

         List<ServerAddress> list = new ArrayList<ServerAddress>();

//      连接数据库   ip 端口

         list.add( new ServerAddress( "10.39.XXX.XXX" , 27010 ));

         MongoClient mongoClient = new MongoClient(list);

         //数据库名称

         DB psdoc = mongoClient.getDB( "qa_db_center" );

         //表明

         DBCollection collection=psdoc.getCollection( "base_user_info" );

        

         BasicDBObject queryObject = null ;

        

         // 时间查询    数据库看到的时间不是真实时间  加8小时后才是正确的时间

         DBObject dbObject = new BasicDBObject();

         String startDate = "2018-03-29 15:59:06" ;

         String endDate = "2018-03-29 16:30:46" ;

         SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );

         dbObject.put( "$gte" , sdf.parse(startDate));

         dbObject.put( "$lte" ,  sdf.parse(endDate));

         queryObject = new BasicDBObject();

         queryObject.put( "create_time" ,dbObject);

         DBCursor find = collection.find(queryObject);

         

         while (find.hasNext()) {

              DBObject next = find.next();

              Object real_name = next.get( "real_name" );

              Object mobile = next.get( "mobile" );

              Object create_time = next.get( "create_time" );

              String str = sdf.format(create_time);

              System.out.println(real_name + "=====" +mobile + "=====" +str);

         }

          System.out.println( "结束" );

        

     }

}

请求页面 默认页 https://blog.csdn.net/qq_27292113/article/details/91876121 【标题】:MongoDB中的日期查询的坑_天马行空-的博客-CSDN博客_mongodb query 日期 【内容】:

在熟悉monggoDB的时候遇到了时间查询的问题代码如下:

上面的代码中查询时间 按mysql 的流程应该查询到 2018-03-29 15:59:06 到2018-03-29 16:30:46 这个区间的数据,但是mongoDB不同,因为mongo中的date类型以UTC(Coordinated Universal Time)存储,就等于GMT(格林尼治标准时)时间。而系统时间使用的是GMT+0800时间,两者正好相差8个小时。也就是用java 代码插入的时间类型的值都会被减8小时。这个坑挺大的不注意很容易出事。

展示一下对比数据便于理解:

上面的圈是查询的条件对应数据库中的数据是2018-03-29T08:30:36.310Z 如下图,但是在java中你写2018-03-29 08:30:36这个时间肯定查不到数据

对比得出数据库中看到的时间和实际时间差8小时,但是查询出来的结果时间还是会被转换回来(不以时间为条件查询的话基本没什么问题)。

记录一下mongoDB中查询区间时间的执行语句:

?

1

db.getCollection( 'base_user_info' ).find({ "create_time" :{ "$gte" :ISODate( "2018-03-29 07:59:06" ), "$lte" :ISODate( "2018-03-29 08:30:46" )}});

base_user_info :表名  create_time:字段名

比较符号对应列表

$gt -------- greater than  > $gte --------- gt equal  >= $lt -------- less than  < $lte --------- lt equal  <= $ne ----------- not equal  != $eq  --------  equal  =

以上为个人经验,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/lMasterSparkl/article/details/109679841

查看更多关于Mongodb 如何将时间戳转换为年月日日期的详细内容...

  阅读:42次