关于输出 YYYY/MM/DD 的问题(ZT)

.NET中DateTime.ToString()的问题

DateTime.ToString()是一个好东西,也非常便于使用,基本上你指定什么他就显示什么,呵呵,没错,是“基本上”,MS有时候不太好用,比如下面这段:
static   void  Main( string [] args)
{
    Console.WriteLine(DateTime.Now.ToString(
" yyyyMMdd " ));
    Console.WriteLine(DateTime.Now.ToString(
" yyyy-MM-dd " ));
    Console.WriteLine(DateTime.Now.ToString(
" yyyy/MM/dd " ));
    Console.WriteLine(DateTime.Now.ToString(
" yyyy年MM月dd日 " ));
    Console.WriteLine(DateTime.Now.ToString(
" yyyy~MM~dd " ));
    Console.Read();
}

你能看出最终的输出结果是什么吗?猜一猜,哪行会和你预想的不一样?

看结果:

20070121
2007 - 01 - 21
2007 - 01 - 21
2007年01月21日
2007 ~ 01 ~ 21

第三行~~~~~~~~~

为什么DateTime.Now.ToString("yyyy/MM/dd")的输出结果不是 2007/01/21 呢?去控制面板里设置一下计算机的短日期格式,发现这个是受计算机短日期格式的影响,可是这个ToString()是不是不应该存在这个问题?不是说好“自定义”的吗?

引申问题:如何用ToString()输出 2007/01/21 这个样子的格式呢?修改计算机设置的那个办法不算数

解决方法倒是有,使用ToString()的另一个重载:
DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo);
不过还是感觉不爽啊

转载于:https://www.cnblogs.com/dating2008/archive/2008/06/24/1229242.html

package com.jsfj.evcall.biz.task.listener; import cn.hutool.core.bean.BeanUtil; import cn.hutool.core.collection.CollectionUtil; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.baomidou.mybatisplus.core.toolkit.BeanUtils; import com.baomidou.mybatisplus.core.toolkit.StringUtils; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.jsfj.common.util.RedisUtil; import com.jsfj.evcall.biz.common.conf.TaskEmergencyConfig; import com.jsfj.evcall.biz.common.constants.task.CarOutStatusEnum; import com.jsfj.evcall.biz.common.util.HttpUtils; import com.jsfj.evcall.biz.task.dao.mapper.ICarOutMapper; import com.jsfj.evcall.biz.task.entity.DispatchInfoDto; import com.jsfj.evcall.biz.task.entity.po.CarOutPo; import com.jsfj.evcall.biz.task.event.DispatchTimeNodeEvent; import com.jsfj.evcall.biz.task.push.CarOutInfoDto; import com.jsfj.evcall.biz.unit.dao.mapper.IAmbMapper; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationListener; import org.springframework.data.redis.connection.RedisServer; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; import java.text.SimpleDateFormat; import java.util.*; import java.util.stream.Collectors; /** * 推送调度信息 */ @Component @Async @Slf4j @ConditionalOnProperty(prefix = "push.suining", name = "enable", havingValue = "true", matchIfMissing = false) public class DispatchTimeNodeEventListener implements ApplicationListener<DispatchTimeNodeEvent> { @Autowired private ICarOutMapper iCarOutMapper; @Autowired private IAmbMapper iAmbMapper; @Autowired private RedisUtil redisUtil; @Autowired private TaskEmergencyConfig taskEmergencyConfig; @Override public void onApplicationEvent(DispatchTimeNodeEvent event) { //获取调度id DispatchInfoDto dto = (DispatchInfoDto) event.getSource(); Long dispatchId = dto.getDispatchId(); log.info("接受到的参数:{}", dispatchId); //查询调度出车信息 List<CarOutPo> carOutPos = iCarOutMapper.selectList(Wrappers.<CarOutPo>lambdaQuery().eq(CarOutPo::getTaskDispatchId, dispatchId)); if (CollectionUtil.isEmpty(carOutPos)) { return; } List<Integer> carOutStatus = CarOutStatusEnum.pushSH(); //过滤满足条件的出车状态 carOutPos = carOutPos.stream().filter(carOut -> carOutStatus.contains(carOut.getStatus()) || CarOutStatusEnum.isCancel(carOut.getStatus())).collect(Collectors.toList()); //不过滤状态,保证当前状态下有值,时间有值,及时补偿,redis只保存推送成功的 List<CarOutPo> newCarOut = new ArrayList<>(); //判断该阶段是否已经推送过数据 for (CarOutPo carOutPo : carOutPos) { //组装redisKey String redisKey = String.format("PushNode:%s:%s", dispatchId, carOutPo.getAmbId()); List<Integer> status = (List<Integer>) redisUtil.get(redisKey); log.info("redis缓冲的数据:{}",JSONArray.toJSONString(status)); if (CollectionUtils.isEmpty(status) || !status.contains(carOutPo.getStatus())) { log.info("节点状态:{},{}",dispatchId,status); List<Integer> integers = status == null ? new ArrayList<>() : status; integers.add(carOutPo.getStatus()); redisUtil.set(redisKey, integers, 24 * 60 * 60 * 2); newCarOut.add(carOutPo); } // 判断是否是最后一个节点:做补偿机制 if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_HOSPITAL.getCode())) { log.info("是否进入补偿机制"); List<Integer> pushSH = CarOutStatusEnum.pushSH(); List<Integer> redisStatus = (List<Integer>) redisUtil.get(redisKey); log.info("进入缓冲机制的redis里面的数据:{}",JSONArray.toJSONString(redisStatus)); pushSH.removeAll(redisStatus); log.info("需要补偿的节点数据:{}",JSONArray.toJSONString(pushSH)); if(CollectionUtil.isNotEmpty(pushSH)){ for (Integer zt : pushSH) { CarOutPo carOutPo1 = BeanUtil.copyProperties(carOutPo, CarOutPo.class); log.info("补偿节点状态:{},{}",dispatchId,zt); List<Integer> integers = new ArrayList<>(redisStatus); integers.add(zt); redisUtil.set(redisKey, integers, 24 * 60 * 60 * 2); carOutPo1.setStatus(zt); newCarOut.add(carOutPo1); } } } } if (CollectionUtil.isEmpty(newCarOut)) { return; } List<CarOutPo> collect = newCarOut.stream().sorted(Comparator.comparing(CarOutPo::getStatus)).collect(Collectors.toList()); collect.forEach(carOutPo -> { CarOutInfoDto build = CarOutInfoDto.builder() .jz_dddh(dispatchId.toString()) .ztdm(Optional.ofNullable(carOutPo.getAmbId()).map(Object::toString).orElse(null)) .ztpz(Optional.ofNullable(carOutPo.getPlateNumber()).filter(StringUtils::isNotBlank).orElse(null)) // .czsj(Optional.ofNullable(carOutPo.getLeaveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)) // .ddxcsj(Optional.ofNullable(carOutPo.getArriveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)) // .jzhzsj(null) // .fcsj(Optional.ofNullable(carOutPo.getReturnTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)) // .rwwcsj(Optional.ofNullable(carOutPo.getCompletedTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)) // .sfzcjs(carOutPo.getCompletedTime() != null ? 1 : 0) .jdmc(Optional.ofNullable(carOutPo.getStatus()).map(CarOutStatusEnum::carOutStatusName).orElse(null)) .ycyy(Optional.ofNullable(carOutPo.getCancelReason()).filter(StringUtils::isNotBlank).orElse(null)).build(); if (carOutPo.getStatus() != null) { if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_DEPARTED.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getLeaveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_SITE.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getArriveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_RETURN.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getReturnTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_HOSPITAL.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getCompletedTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (CarOutStatusEnum.isCancel(carOutPo.getStatus())) { build.setJlsj(Optional.ofNullable(carOutPo.getCancelTime()).map(item-> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } } String param = JSONObject.toJSONString(build); retryPush( param,dispatchId); }); } private static final int MAX_RETRIES = 3; private static final long RETRY_INTERVAL_MS = 1000; // 每次重试间隔1秒 public boolean retryPush( String param,Long dispatchId) { int attempt = 0; while (attempt < MAX_RETRIES) { try { if (executePush(param,dispatchId)) { return true; // 推送成功,直接返回 } } catch (Exception e) { log.warn("推送失败(第{}次尝试): {}", attempt + 1, e.getMessage()); } attempt++; if (attempt < MAX_RETRIES) { try { Thread.sleep(RETRY_INTERVAL_MS); // 等待一段时间后重试 } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error("线程中断:{}", ie.getMessage()); } } } return false; // 所有重试均失败 } private boolean executePush(String param,Long dispatchId) { log.info("推送的参数:{}", param); log.info("推送地址:{}", taskEmergencyConfig.getBaseUrl() + taskEmergencyConfig.getPushDispatchInfoUrl()); log.info("推送header参数:{}", taskEmergencyConfig.getThirdInstitutionID()); String resultJson = HttpUtils.sendHttps(taskEmergencyConfig.getBaseUrl() + taskEmergencyConfig.getPushDispatchInfoUrl(), taskEmergencyConfig.getThirdInstitutionID(), param); log.info("响应数据:{}", resultJson); if (StringUtils.isNotBlank(resultJson)) { JSONObject jsonObject = JSONObject.parseObject(resultJson); if (!Objects.equals(jsonObject.getString("resultcode"), "0")) { log.error("响应错误提示:{}", jsonObject.getString("message")); //失败的要贴出并补偿 //并将发送数据存入redis中做备份 String key = String.format("TimeNode:%s", dispatchId); redisUtil.set(key, param); return false; } return true; } return false; } } 以上为源代码,根据源代码优化为CAR_DEPARTED ,CAR_DEPARTED,CAR_RETURN,CAR_ARRIVED_HOSPITAL 有序发送, retryPush失败不存redis
05-28
/** * 推送调度信息 */ @Component @Async @Slf4j @ConditionalOnProperty(prefix = "push.suining", name = "enable", havingValue = "true", matchIfMissing = false) public class DispatchTimeNodeEventListener implements ApplicationListener<DispatchTimeNodeEvent> { @Autowired private ICarOutMapper iCarOutMapper; @Autowired private IAmbMapper iAmbMapper; @Autowired private RedisUtil redisUtil; @Autowired private TaskEmergencyConfig taskEmergencyConfig; @Override public void onApplicationEvent(DispatchTimeNodeEvent event) { //获取调度id DispatchInfoDto dto = (DispatchInfoDto) event.getSource(); Long dispatchId = dto.getDispatchId(); log.info("接受到的参数:{}", dispatchId); //查询调度出车信息 List<CarOutPo> carOutPos = iCarOutMapper.selectList(Wrappers.<CarOutPo>lambdaQuery().eq(CarOutPo::getTaskDispatchId, dispatchId)); if (CollectionUtil.isEmpty(carOutPos)) { return; } List<Integer> carOutStatus = CarOutStatusEnum.pushSH(); //过滤满足条件的出车状态 carOutPos = carOutPos.stream().filter(carOut -> carOutStatus.contains(carOut.getStatus()) || CarOutStatusEnum.isCancel(carOut.getStatus())).collect(Collectors.toList()); //不过滤状态,保证当前状态下有值,时间有值,及时补偿,redis只保存推送成功的 List<CarOutPo> newCarOut = new ArrayList<>(); //判断该阶段是否已经推送过数据 for (CarOutPo carOutPo : carOutPos) { //组装redisKey String redisKey = String.format("PushNode:%s:%s", dispatchId, carOutPo.getAmbId()); List<Integer> status = (List<Integer>) redisUtil.get(redisKey); log.info("redis缓冲的数据:{}",JSONArray.toJSONString(status)); if (CollectionUtils.isEmpty(status) || !status.contains(carOutPo.getStatus())) { log.info("节点状态:{},{}",dispatchId,status); List<Integer> integers = status == null ? new ArrayList<>() : status; integers.add(carOutPo.getStatus()); redisUtil.set(redisKey, integers, 24 * 60 * 60 * 2); newCarOut.add(carOutPo); } // 判断是否是最后一个节点:做补偿机制 if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_HOSPITAL.getCode())) { log.info("是否进入补偿机制"); List<Integer> pushSH = CarOutStatusEnum.pushSH(); List<Integer> redisStatus = (List<Integer>) redisUtil.get(redisKey); log.info("进入缓冲机制的redis里面的数据:{}",JSONArray.toJSONString(redisStatus)); pushSH.removeAll(redisStatus); log.info("需要补偿的节点数据:{}",JSONArray.toJSONString(pushSH)); if(CollectionUtil.isNotEmpty(pushSH)){ for (Integer zt : pushSH) { CarOutPo carOutPo1 = BeanUtil.copyProperties(carOutPo, CarOutPo.class); log.info("补偿节点状态:{},{}",dispatchId,zt); List<Integer> integers = new ArrayList<>(redisStatus); integers.add(zt); redisUtil.set(redisKey, integers, 24 * 60 * 60 * 2); carOutPo1.setStatus(zt); newCarOut.add(carOutPo1); } } } } if (CollectionUtil.isEmpty(newCarOut)) { return; } List<CarOutPo> collect = newCarOut.stream().sorted(Comparator.comparing(CarOutPo::getStatus)).collect(Collectors.toList()); collect.forEach(carOutPo -> { CarOutInfoDto build = CarOutInfoDto.builder() .jz_dddh(dispatchId.toString()) .ztdm(Optional.ofNullable(carOutPo.getAmbId()).map(Object::toString).orElse(null)) .ztpz(Optional.ofNullable(carOutPo.getPlateNumber()).filter(StringUtils::isNotBlank).orElse(null)) .jdmc(Optional.ofNullable(carOutPo.getStatus()).map(CarOutStatusEnum::carOutStatusName).orElse(null)) .ycyy(Optional.ofNullable(carOutPo.getCancelReason()).filter(StringUtils::isNotBlank).orElse(null)).build(); if (carOutPo.getStatus() != null) { if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_DEPARTED.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getLeaveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_SITE.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getArriveTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_RETURN.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getReturnTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (Objects.equals(carOutPo.getStatus(), CarOutStatusEnum.CAR_ARRIVED_HOSPITAL.getCode())) { build.setJlsj(Optional.ofNullable(carOutPo.getCompletedTime()).map(item -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } else if (CarOutStatusEnum.isCancel(carOutPo.getStatus())) { build.setJlsj(Optional.ofNullable(carOutPo.getCancelTime()).map(item-> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(item)).orElse(null)); } } String param = JSONObject.toJSONString(build); retryPush( param,dispatchId); }); } private static final int MAX_RETRIES = 3; private static final long RETRY_INTERVAL_MS = 1000; // 每次重试间隔1秒 public boolean retryPush( String param,Long dispatchId) { int attempt = 0; while (attempt < MAX_RETRIES) { try { if (executePush(param,dispatchId)) { return true; // 推送成功,直接返回 } } catch (Exception e) { log.warn("推送失败(第{}次尝试): {}", attempt + 1, e.getMessage()); } attempt++; if (attempt < MAX_RETRIES) { try { Thread.sleep(RETRY_INTERVAL_MS); // 等待一段时间后重试 } catch (InterruptedException ie) { Thread.currentThread().interrupt(); log.error("线程中断:{}", ie.getMessage()); } } } return false; // 所有重试均失败 } private boolean executePush(String param,Long dispatchId) { log.info("推送的参数:{}", param); log.info("推送地址:{}", taskEmergencyConfig.getBaseUrl() + taskEmergencyConfig.getPushDispatchInfoUrl()); log.info("推送header参数:{}", taskEmergencyConfig.getThirdInstitutionID()); String resultJson = HttpUtils.sendHttps(taskEmergencyConfig.getBaseUrl() + taskEmergencyConfig.getPushDispatchInfoUrl(), taskEmergencyConfig.getThirdInstitutionID(), param); log.info("响应数据:{}", resultJson); if (StringUtils.isNotBlank(resultJson)) { JSONObject jsonObject = JSONObject.parseObject(resultJson); if (!Objects.equals(jsonObject.getString("resultcode"), "0")) { log.error("响应错误提示:{}", jsonObject.getString("message")); //失败的要贴出并补偿 //并将发送数据存入redis中做备份 String key = String.format("TimeNode:%s", dispatchId); redisUtil.set(key, param); return false; } return true; } return false; } } 推送代码如上,根据以上代码优化逻辑,保证推送状态有序按照CAR_DEPARTED、CAR_ARRIVED_SITE、CAR_RETURN和CAR_ARRIVED_HOSPITAL按照有序推送,retryPush失败后不保存推送当前状态,输出完整的代码
05-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值