我的数据字段以日期格式存储,例如“yyyy / MM / dd HH:mm:ss”。我想使用orderby按日期对数据进行排序,但我该怎么做
我通过代码执行此操作,但需要很长时间才能处理大量代码
public void sortBy_Desc(String SortBy) {
int size = universityData.size();
int after;
for (int m = size; m >= 0; m--) {
for (int before = 0; before < size - 1; before++) {
after = before + 1;
long first = 0, second = 0;
if (SortBy.equals(Data.EXAM_DATE)) {
first = convertStringToDate(examData.get(before).getExam_date()).getTime();
second = convertStringToDate(examData.get(after).getExam_date()).getTime();
}
else if (SortBy.equals(Data.REG_DATE)) {
first = convertStringToDate(examData.get(before).getReg_end_date()).getTime();
second = convertStringToDate(examData.get(after).getReg_end_date()).getTime();
}
else if (SortBy.equals(Data.FEE)) {
String fee = getCurrencyType(examData.get(before).getExam_fee()).get(0);
first = Integer.parseInt(fee);
fee = getCurrencyType(examData.get(after).getExam_fee()).get(0);
second = Integer.parseInt(fee);
}
if (first < second) {
swapData(before, after);
}
}
}
}
答案 0 :(得分:2)
正如Doug Stevenson所提到的,你应该更好地将你的日期存储为String。最佳选择是将您的日期转换为自1970年1月1日00:00:00 GMT以来的毫秒数
在Java中,这是以这种方式完成的
package com.demo.configuration;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.demo.environment.DemoEnvironment;
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
entityManagerFactoryRef = "entityManagerFactory",
basePackages = { "com.demo.dao.oracle" })
public class OracleConfiguration {
DemoEnvironment env = new DemoEnvironment();
@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix="spring.oracle.datasource")
public DataSource dataSource() {
return DataSourceBuilder.create().build();
}
@Primary
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(
EntityManagerFactoryBuilder builder,
@Qualifier("dataSource") DataSource dataSource) {
return builder
.dataSource(dataSource)
.packages("com.demo.entity")
.persistenceUnit("DEMO")
.build();
}
@Primary
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
@Primary
@Bean(name = "sessionFactory")
public HibernateJpaSessionFactoryBean sessionFactory() {
return new HibernateJpaSessionFactoryBean();
}
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
};
}
@Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("http://localhost:7001");
String allowedOrigin = this.env.getAllowedOrigin();
config.addAllowedOrigin(allowedOrigin);
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(0);
return bean;
}
@Bean
public MultipartResolver multipartResolver() {
return new CommonsMultipartResolver();
}
}
pom.xml:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
application.properties:
spring.http.multipart.enabled=false
Controller:
/**
*
*/
package com.demo.controller;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.InvalidMediaTypeException;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartResolver;
import com.demo.entity.Atchmnt;
import com.demo.environment.DemoEnvironment;
import com.demo.service.AttachmentService;
import com.demo.util.Base64Util;
/**
* @author Denis
*
*/
@RequestMapping(value = "/")
@RestController
public class RestUploadController {
private final Logger log = Logger.getLogger(this.getClass());
DemoEnvironment env = new DemoEnvironment();
@Autowired
private AttachmentService attachmentService;
@Autowired
private MultipartResolver multipartResolver;
// private String uploadFolder = "c://temp//"; // this needs to be in
// the application.properties file.
private String uploadFolder = env.getFilesDirectory();
// 3.1.2 Multiple file upload
// @PostMapping("/api/upload/multi")
// @Consumes(MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseBody
@RequestMapping(value = { "/upload/multi/{fein}" },
method = { RequestMethod.POST },
consumes = {MediaType.MULTIPART_FORM_DATA_VALUE},
produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<?> uploadFileMulti(
@PathVariable Long fein,
// @RequestParam("extraField") String extraField,
@RequestPart("uploadFiles") MultipartFile[] myFiles,
HttpServletRequest req
) {
log.info("Multiple file upload!");
// Get file name
// String uploadedFileName = Arrays.stream(uploadFiles).map(x ->
// x.getOriginalFilename())
// .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" ,
// "));
//
// if (StringUtils.isEmpty(uploadedFileName)) {
// return new ResponseEntity("please select a file!", HttpStatus.OK);
// }
// Check for empty files.
for (MultipartFile myFile : myFiles) {
log.info("Attempting to upload of files=" + myFile.getOriginalFilename());
if (myFile.isEmpty()) {
log.error("No file specified!");
return new ResponseEntity<>("No file specified!", HttpStatus.BAD_REQUEST);
}
}
try {
saveUploadedFiles( fein, Arrays.asList(myFiles));
} catch (IOException e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>("Successfully uploaded - file(s).", HttpStatus.OK);
}
// save file
private void saveUploadedFiles(Long fein, List<MultipartFile> files) throws IOException {
for (MultipartFile file : files) {
log.info("Attempting to upload the requested file.");
if (file.isEmpty()) {
continue; // next pls
}
byte[] bytes = file.getBytes();
String folderPath = createFileSystemFolder( uploadFolder + "/" + fein );
log.info("saving file=" + file.getOriginalFilename());
Path path = Paths.get(folderPath + file.getOriginalFilename());
Files.write(path, bytes);
}
}
public String createFileSystemFolder(String folderPath) {
log.info("createFileSystemFolder(): attempting to create folder=" + folderPath );
File file = new File(folderPath);
if (!file.exists()) {
file.mkdirs();
} else {
log.error("createFileSystemFolder(): failed to create the folder.");
}
return folderPath + "/";
}
}
或以下Java 8
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = sdf.parse(myDate);
long millisSinceEpoch = date.getTime();
然后很容易订购。如果您想获得相反的订单(即最近的日期),您可以存储
long millisSinceEpoch = LocalDateTime.parse(myDate, DateTimeFormatter.ofPattern("uuuu/MM/dd HH:mm:ss"))
.atOffset(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();