import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* Description: zip管理器
*
* @version 1.0.0
*/
public class ZipManager {
static final int BUFFER = 8192;
/**
* zip压缩功能测试. 将d:\\temp\\zipout目录下的所有文件连同子目录压缩到d:\\temp\\out.zip.
*
* @param baseDir
* 所要压缩的目录名(包含绝对路径)
* @param objFileName
* 压缩后的文件名
* @throws Exception
*/
public static void createZip(String baseDir, String objFileName) throws Exception {
File folderObject = new File(baseDir);
if (folderObject.exists()) {
List<File> fileList = getSubFiles(new File(baseDir));
// 压缩文件名
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFileName));
ZipEntry ze = null;
byte[] buf = new byte[1024];
int readLen = 0;
for (int i = 0; i < fileList.size(); i++) {
File f = (File) fileList.get(i);
System.out.println("Adding: " + f.getPath() + f.getName());
// 创建一个ZipEntry,并设置Name和其它的一些属性
ze = new ZipEntry(getAbsFileName(baseDir, f));
ze.setSize(f.length());
ze.setTime(f.lastModified());
// 将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(f));
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
}
zos.close();
} else {
throw new Exception("this folder isnot exist!");
}
}
/**
* zip压缩功能测试. 将指定文件压缩后存到一压缩文件中
*
* @param baseDir
* 所要压缩的文件名
* @param objFileName
* 压缩后的文件名
* @return 压缩后文件的大小
* @throws Exception
*/
public static long createFileToZip(String zipFilename, String sourceFileName) throws Exception {
File sourceFile = new File(sourceFileName);
byte[] buf = new byte[1024];
// 压缩文件名
File objFile = new File(zipFilename);
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFile));
ZipEntry ze = null;
// 创建一个ZipEntry,并设置Name和其它的一些属性
ze = new ZipEntry(sourceFile.getName());
ze.setSize(sourceFile.length());
ze.setTime(sourceFile.lastModified());
// 将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));
int readLen = -1;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
zos.close();
return objFile.length();
}
/**
* zip压缩功能测试. 将指定文件压缩后存到一压缩文件中
*
* @param baseDir
* 所要压缩的文件名
* @param objFileName
* 压缩后的文件名
* @return 压缩后文件的大小
* @throws Exception
*/
public static long createFileToZip(File sourceFile, File zipFile) throws IOException {
byte[] buf = new byte[1024];
// 压缩文件名
File objFile = zipFile;
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(objFile));
ZipEntry ze = null;
// 创建一个ZipEntry,并设置Name和其它的一些属性
ze = new ZipEntry(sourceFile.getName());
ze.setSize(sourceFile.length());
ze.setTime(sourceFile.lastModified());
// 将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(sourceFile));
int readLen = -1;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
zos.write(buf, 0, readLen);
}
is.close();
zos.close();
return objFile.length();
}
/**
* 测试解压缩功能. 将d:\\download\\test.zip连同子目录解压到d:\\temp\\zipout目录下。
* @param sourceZip
* @param outFileName
* @param suffix 只解压 后缀为suffix文件
* @throws IOException
*/
public static void releaseZipToFile(String sourceZip, String outFileName,String suffix) throws IOException {
ZipFile zfile = new ZipFile(sourceZip);
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024 * 8];
while (zList.hasMoreElements()) {
// 从ZipFile中得到一个ZipEntry
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
continue;
}
if(suffix!=null){
String name=ze.getName();
if(!name.endsWith(suffix)){
continue;
}
}
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
OutputStream os = null;
os = new BufferedOutputStream(new FileOutputStream(getRealFileName(outFileName, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
// //Log.i("ZipManager", "[releaseZipToFile]"+"Extracted: " +
// ze.getName());
}
zfile.close();
}
public static void releaseZipToFile(String sourceZip, String outFileName) throws IOException {
releaseZipToFile(sourceZip,outFileName,null);
}
public static File releaseFileFromZip(String sourceZip,String outFilePath,String fileName) throws IOException{
byte[] buf = new byte[1024 * 8];
ZipFile zfile = new ZipFile(sourceZip);
ZipEntry ze=zfile.getEntry(fileName);
File destFile = null;
if(ze!=null){
OutputStream os = null;
destFile = getRealFileName(outFilePath, ze.getName());
os = new BufferedOutputStream(new FileOutputStream(destFile));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
}
zfile.close();
return destFile;
}
public static void releaseFileFromZip(String sourceZip, String sourceEntryName, String destDir, String destFileName) throws IOException{
byte[] buf = new byte[1024 * 8];
ZipFile zfile = new ZipFile(sourceZip);
ZipEntry ze=zfile.getEntry(sourceEntryName);
if(ze!=null){//文件的情况
OutputStream os = null;
InputStream is = null;
try {
os = new BufferedOutputStream(new FileOutputStream(getRealFileName(destDir, destFileName)));
is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
os.write(buf, 0, readLen);
}
} finally {
if(is != null) {
is.close();
is = null;
}
if(os != null) {
os.close();
os = null;
}
}
} else {//有文件夹的情况
Enumeration<ZipEntry> n = (Enumeration<ZipEntry>) zfile.entries();
while(n.hasMoreElements()) {
ZipEntry zipFile = n.nextElement();
if(zipFile!=null){
String entryname = zipFile.getName();
if(entryname.startsWith(sourceEntryName)) {
String endPath = entryname.substring(sourceEntryName.length());
if(endPath.endsWith("/")) {//文件夹
File file = new File(destDir + destFileName + endPath);
if(!file.exists()) {
file.mkdirs();
}
} else {//文件
OutputStream os = null;
InputStream is = null;
try {
os = new BufferedOutputStream(new FileOutputStream(getRealFileName(destDir + destFileName, endPath)));
is = new BufferedInputStream(zfile.getInputStream(zipFile));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
os.write(buf, 0, readLen);
}
} finally {
if(is != null) {
is.close();
is = null;
}
if(os != null) {
os.close();
os = null;
}
}
}
}
}
}
}
zfile.close();
}
/**
* 解压ZIP包, 保留目录结构。
* @throws IOException
*/
public static ArrayList<Object> ectract(String sZipPathFile, String sDestPath, boolean autoRename,boolean isStop) throws IOException {
ArrayList<Object> allFileName = new ArrayList<Object>();
// 先指定压缩档的位置和档名,建立FileInputStream对象
FileInputStream fins = new FileInputStream(sZipPathFile);
// 将fins传入ZipInputStream中
ZipInputStream zins = new ZipInputStream(fins);
ZipEntry ze = null;
byte ch[] = new byte[BUFFER];
while ((ze = zins.getNextEntry()) != null) {
if (isStop) {
return null;
}
String name = ze.getName();
name = name.replace('\\', '/');
name = name.replaceAll("\\s", "%20");
File zfile = new File(sDestPath + name);
File fpath = new File(zfile.getParentFile().getPath());
if (ze.isDirectory()) {
if (!zfile.exists())
zfile.mkdirs();
zins.closeEntry();
} else {
if (!fpath.exists())
fpath.mkdirs();
FileOutputStream fouts = new FileOutputStream(zfile);
int i;
allFileName.add(zfile.getAbsolutePath());
while ((i = zins.read(ch,0,BUFFER)) != -1)
fouts.write(ch, 0, i);
zins.closeEntry();
fouts.close();
}
}
fins.close();
zins.close();
return allFileName;
}
// /**
// * 测试解压缩功能. 将d:\\download\\test.zip连同子目录解压到d:\\temp\\zipout目录下.
// *
// * @throws Exception
// */
// @SuppressWarnings("unchecked")
// public static void releaseDecodeZipToFile(String sourceZip, String
// outFileName, String password) throws Exception {
// SecretKeySpec dks = new SecretKeySpec(password.getBytes(), "AES");
// SecureRandom sr = new SecureRandom();
// Cipher ciphers = Cipher.getInstance("AES/CBC/PKCS5Padding");
// IvParameterSpec spec = new IvParameterSpec(dks.getEncoded());
// ciphers.init(Cipher.DECRYPT_MODE, dks, spec, sr);
//
// ZipFile zfile = new ZipFile(sourceZip);
// System.out.println(zfile.getName());
// Enumeration zList = zfile.entries();
// ZipEntry ze = null;
// byte[] buf = new byte[1024 * 8];
// while (zList.hasMoreElements()) {
// // 从ZipFile中得到一个ZipEntry
// ze = (ZipEntry) zList.nextElement();
// if (ze.isDirectory()) {
// continue;
// }
// // 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
// OutputStream os = new BufferedOutputStream(new
// FileOutputStream(getRealFileName(outFileName, ze.getName())));
// InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
// int readLen = 0;
// while ((readLen = is.read(buf, 0, 1024 * 8)) != -1) {
// os.write(ciphers.doFinal(buf), 0, readLen);
// }
// is.close();
// os.close();
// // //Log.i("ZipManager", "[releaseZipToFile]"+"Extracted: " +
// // ze.getName());
// }
// zfile.close();
// }
/**
* 取得指定目录下的所有文件列表,包括子目录.
*
* @param baseDir
* File 指定的目录
* @return 包含java.io.File的List
*/
public static List<File> getSubFiles(File baseDir) {
List<File> ret = new ArrayList<File>();
// File base=new File(baseDir);
File[] tmp = baseDir.listFiles();
for (int i = 0; i < tmp.length; i++) {
if (tmp[i].isFile()) {
ret.add(tmp[i]);
}
if (tmp[i].isDirectory()) {
ret.addAll(getSubFiles(tmp[i]));
}
}
return ret;
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
* @throws IOException
*/
private static File getRealFileName(String baseDir, String absFileName) throws IOException {
String[] dirs = absFileName.split("/");
// System.out.println(dirs.length);
File ret = new File(baseDir);
// System.out.println(ret);
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {
ret.mkdirs();
}
String parentPath = ret.getAbsolutePath();
ret = new File(ret, new String(dirs[dirs.length - 1].getBytes()));
if (!ret.exists()) {
try {
ret.createNewFile();
} catch (Exception e) {
String fileName = new String(dirs[dirs.length - 1].getBytes());
int idx = fileName.lastIndexOf(".");
String ext = "";
if (idx >= 0) {
ext = fileName.substring(idx);
}
ret = new File(parentPath, "" + System.currentTimeMillis() + ext);
ret.createNewFile();
}
}
return ret;
}
/**
* 给定根目录,返回另一个文件名的相对路径,用于zip文件中的路径.
*
* @param baseDir
* java.lang.String 根目录
* @param realFileName
* java.io.File 实际的文件名
* @return 相对文件名
*/
public static String getAbsFileName(String baseDir, File realFileName) {
File real = realFileName;
File base = new File(baseDir);
String ret = real.getName();
while (true) {
real = real.getParentFile();
if (real == null)
break;
if (real.equals(base))
break;
else {
ret = real.getName() + "/" + ret;
}
}
return ret;
}
@SuppressWarnings("unchecked")
public void testReadZip(String zipPath, String outPath) throws Exception {
ZipFile zfile = new ZipFile(zipPath);
System.out.println(zfile.getName());
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
// 从ZipFile中得到一个ZipEntry
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
continue;
}
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
OutputStream os = new BufferedOutputStream(new FileOutputStream(getRealFileName(outPath, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
//Log.i("ZipManager", "[testReadZip]" + "Extracted: " + ze.getName());
}
zfile.close();
}
public static byte[] convertStringtoGzip(List<String> contents) {
ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
GZIPOutputStream gop = null;
try {
gop = new GZIPOutputStream(arrayOutputStream);
for (String content : contents) {
byte[] contentByte = content.getBytes();
// //Log.i("SPACE", content);
gop.write(contentByte, 0, contentByte.length);
}
gop.finish();
} catch (Exception e) {
return null;
} finally {
try {
gop.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return arrayOutputStream.toByteArray();
}
@SuppressWarnings("static-access")
public static void main(String args[]) {
// ZipManager manager = new ZipManager();
// try {
// //manager.unZip("c:\\testNpk.npk", "c:\\test");
// } catch (Exception e) {
// }
// System.out.println("over");
}
}
@implementation ViewControllerFactory
#pragma mark ====== 适配iphone5公用的方法 ======
+(id)createViewControllerByControllerName:(NSString*) controllerName {
if (controllerName == nil || [controllerName isEqualToString:@""]) {
return nil;
}
NSString *controllerXibName = nil;
if (isIPhone5) {
controllerXibName = [NSString stringWithFormat:@"%@_iphone5",controllerName];
}else {
controllerXibName = controllerName;
}
Class class = NSClassFromString(controllerName);
return [[[class alloc] initWithNibName:controllerXibName bundle:nil] autorelease];
}
#pragma mark ====== 导航栏公用的方法 ======
+(void)initNavigationbar:(UIViewController *)tempViewController centerName:(NSString *)centerName rightButtonName:(NSString *)rightButtonName leftImage:(NSString *)leftImage rightImage:(NSString *)rightImage{
//自定义返回按钮。
UIButton *tempButton = [UIButton buttonWithType:UIButtonTypeCustom];
[tempButton setBackgroundImage:[UIImage imageNamed:leftImage] forState:UIControlStateNormal];
tempButton.frame=CGRectMake(0, 0, 50, 30);
[tempButton addTarget:tempViewController action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *leftButton = [[UIBarButtonItem alloc]initWithCustomView:tempButton];
tempViewController.navigationItem.leftBarButtonItem=leftButton;
[leftButton release];
//解除绑定按钮。
UIButton *tempButton1 = [UIButton buttonWithType:UIButtonTypeCustom];
[tempButton1 setTitle:rightButtonName forState:UIControlStateNormal];
[tempButton1 setBackgroundImage:[UIImage imageNamed:rightImage] forState:UIControlStateNormal];
tempButton1.frame=CGRectMake(0, 0, 80, 30);
[tempButton1 addTarget:tempViewController action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *rightButton = [[UIBarButtonItem alloc]initWithCustomView:tempButton1];
tempViewController.navigationItem.rightBarButtonItem=rightButton;
[rightButton release];
//显示导航栏。
[UIView animateWithDuration:0.4 animations:^{
tempViewController.navigationController.navigationBarHidden = NO;
tempViewController.navigationController.navigationBar.tintColor = [UIColor blackColor];
tempViewController.navigationItem.title=centerName;
}];
}
#import <Foundation/Foundation.h>
@interface CalculatorSingleton : NSObject
@property (nonatomic, strong) NSCalendar *calendar;
+ (CalculatorSingleton *) sharedInstance;
- (int)numberOfWeeksInMonthContainingDate:(NSDate *)date;
- (NSDate *)firstDayOfMonthContainingDate:(NSDate *)date;
- (NSDate *)lastDayOfMonthContainingDate:(NSDate *)date;
- (BOOL)dateIsToday:(NSDate *)date;
- (NSDate*)getLocaleDate;
+ (NSDate*)getLocaleDate;
- (int)dayOfWeekForDate:(NSDate *)date;
- (NSDate *)nextDay:(NSDate *)date;
- (NSDate*)previousDay:(NSDate*)date;
- (NSDate*)nextMonth:(NSDate*)date;
- (NSDate*)previousMonth:(NSDate*)date;
- (BOOL)date:(NSDate*)date1 InSameMonthWith:(NSDate*)date2;
- (int)weekNumberInMonthForDate:(NSDate *)date;
- (NSString*)formatDate:(NSDate*)date;
- (int)year:(NSDate*)date;
- (int)month:(NSDate*)date;
- (int)day:(NSDate*)date;
- (int)hour:(NSDate*)date;
- (int)minute:(NSDate*)date;
- (int)second:(NSDate*)date;
- (NSString*)senselFormatDate:(NSDate*)date;
- (NSString*)HMS:(NSDate*)date;
-(NSDate *)nextOrPreviousDay:(NSDate *)date day:(NSInteger)day;
- (NSDate*)localToGMT:(NSDate*)date;
-(NSDate *)GMTToLacal:(NSDate *)date;
- (BOOL)isSameDay:(NSDate*)oneDate withAnotherDay:(NSDate*)anotherDate;
- (NSString*)getChineseCalendarWithDate:(NSDate *)date;
- (NSString*)getMemoryLunarShow;
- (NSDate*)nextYear:(NSDate*)date;
- (NSDate*)previousYear:(NSDate*)date;
@end
#import "CalculatorSingleton.h"
@implementation CalculatorSingleton
@synthesize calendar=_calendar;
staticCalculatorSingleton *_sharedInstance = nil;
//类方法
+ (CalculatorSingleton*)sharedInstance
{
if (_sharedInstance != nil) {
return_sharedInstance;
}
@synchronized(self) {
if (_sharedInstance == nil) {
[[[selfalloc] init] autorelease];
}
}
return_sharedInstance;
}
+ (id)allocWithZone:(NSZone*)zone
{
@synchronized(self) {
if (_sharedInstance == nil) {
_sharedInstance = [superallocWithZone:zone];
return_sharedInstance;
}
}
NSAssert(NO, @ "[BlockBackground alloc] explicitly called on singleton class.");
returnnil;
}
- (id)copyWithZone:(NSZone*)zone
{
returnself;
}
- (id)retain
{
returnself;
}
-(unsigned)retainCount
{
returnUINT_MAX;
}
-(onewayvoid)release
{
}
-(id)autorelease
{
returnself;
}
#pragma mark -
-(id)init
{
self=[superinit];
if(self){
// NSCalendar* calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
// NSLog(@"[NSLocale systemLocale]=%@",[NSLocale systemLocale]);
// //[calendar setLocale:[NSLocale systemLocale]];
// [self.calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
// [calendar setFirstWeekday:2];//从周一开始
// self.calendar = calendar;
// NSDate* today = [self getLocaleDate];
// NSLog(@"%@",today);
self.calendar=[[[NSCalendaralloc]initWithCalendarIdentifier:NSGregorianCalendar]autorelease];
[self.calendarsetLocale:[NSLocalesystemLocale]];
[self.calendarsetTimeZone:[NSTimeZonetimeZoneWithAbbreviation:@"GMT"]];
[self.calendarsetFirstWeekday:1];//从周日开始
NSDate* today =[selfgetLocaleDate];
NSLog(@"今天是%@",today);
}
returnself;
}
-(void)dealloc
{
[_calendarrelease];
[superdealloc];
}
#pragma mark -根据某天返回这天所在月有几个星期
-(int)numberOfWeeksInMonthContainingDate:(NSDate*)date {
return[self.calendarrangeOfUnit:NSWeekCalendarUnitinUnit:NSMonthCalendarUnitforDate:date].length;
}
#pragma mark -根据某天得到本天所在月的第一天
-(NSDate*)firstDayOfMonthContainingDate:(NSDate*)date {
NSDateComponents*comps =[self.calendarcomponents:(NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit)fromDate:date];
[comps setDay:1];
NSDate* returnDate =[self.calendardateFromComponents:comps];
return returnDate;
}
#pragma mark -根据某天得到本天所在月的最后一天
-(NSDate*)lastDayOfMonthContainingDate:(NSDate*)date {
// NSDateComponents *comps = [self.calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
// [comps setMonth:1];
// [comps setDay:0];
// NSDate* returnDate = [self.calendar dateFromComponents:comps];
// return returnDate;
NSDate* firstDay=[selffirstDayOfMonthContainingDate:date];
NSDate* nextMonthFirstDay=[selfnextMonth:firstDay];
return[selfpreviousDay:nextMonthFirstDay];
}
#pragma mark -判断是不是今天
-(BOOL)dateIsToday:(NSDate*)date {
NSDateComponents*otherDay =[self.calendarcomponents:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnitfromDate:date];
NSDateComponents*today =[self.calendarcomponents:NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnitfromDate:[selfgetLocaleDate]];
BOOL isToday=([today day]==[otherDay day]&&
[today month]==[otherDay month]&&
[today year]==[otherDay year]&&
[today era]==[otherDay era]);
//NSLog(@"date=%@,isToday=%d",date,isToday);
return isToday;
}
#pragma mark -获取本地时间
-(NSDate*)getLocaleDate{
NSDate*date =[NSDatedate];
NSTimeZone*zone =[NSTimeZonesystemTimeZone];
NSInteger interval =[zone secondsFromGMTForDate: date];
NSDate* realDate =[date dateByAddingTimeInterval: interval];
return realDate;
}
-(NSDate*)GMTToLocal{
NSDate* date =[[NSDatedate]dateByAddingTimeInterval:[[NSTimeZonesystemTimeZone]secondsFromGMT]];
return date;
}
-(NSDate*)localToGMT:(NSDate*)date{
return[date dateByAddingTimeInterval:-[[NSTimeZonesystemTimeZone]secondsFromGMT]];
}
-(NSDate*)GMTToLacal:(NSDate*)date{
return[date dateByAddingTimeInterval:[[NSTimeZonesystemTimeZone]secondsFromGMT]];
}
+(NSDate*)getLocaleDate{
NSDate*date =[NSDatedate];
NSTimeZone*zone =[NSTimeZonesystemTimeZone];
NSInteger interval =[zone secondsFromGMTForDate: date];
NSDate* realDate =[date dateByAddingTimeInterval: interval];
return realDate;
}
#pragma mark -根据某天返回这一天是星期几
-(int)dayOfWeekForDate:(NSDate*)date {
NSDateComponents*comps =[self.calendarcomponents:NSWeekdayCalendarUnitfromDate:date];
// NSLog(@"comps.weekday=%d",comps.weekday);
return comps.weekday;
}
-(int)weekNumberInMonthForDate:(NSDate*)date {
NSDateComponents*comps =[self.calendarcomponents:(NSWeekOfMonthCalendarUnit)fromDate:date];
return comps.weekOfMonth;
}
#pragma mark -获取date的昨天,明天,下个月,上个月
-(NSDate*)nextDay:(NSDate*)date {
NSDateComponents*comps =[[NSDateComponentsalloc]init];
[comps setDay:1];
NSDate* returnDate =[self.calendardateByAddingComponents:comps toDate:date options:0];
[comps release];
return returnDate;
}
-(NSDate*)nextOrPreviousDay:(NSDate*)date day:(NSInteger)day{
NSDateComponents*comps =[[[NSDateComponentsalloc]init]autorelease];
[comps setDay:day];
return[self.calendardateByAddingComponents:comps toDate:date options:0];
}
-(NSDate*)previousDay:(NSDate*)date{
NSDateComponents*comps =[[[NSDateComponentsalloc]init]autorelease];
[comps setDay:-1];
return[self.calendardateByAddingComponents:comps toDate:date options:0];
}
-(NSDate*)nextMonth:(NSDate*)date{
NSDateComponents*comps =[[[NSDateComponentsalloc]init]autorelease];
[comps setMonth:1];
return[self.calendardateByAddingComponents:comps toDate:date options:0];
}
-(NSDate*)nextYear:(NSDate*)date{
NSDateComponents*comps =[[[NSDateComponentsalloc]init]autorelease];
[comps setYear:1];
return[self.calendardateByAddingComponents:comps toDate:date options:0];
}
-(NSDate*)previousYear:(NSDate*)date{
NSDateComponents*comps =[[[NSDateComponentsalloc]init]autorelease];
[comps setYear:-1];
return[self.calendardateByAddingComponents:comps toDate:date options:0];
}
-(NSDate*)previousMonth:(NSDate*)date{
NSDateComponents*comps =[[[NSDateComponentsalloc]init]autorelease];
[comps setMonth:-1];
return[self.calendardateByAddingComponents:comps toDate:date options:0];
}
#pragma mark -
-(BOOL)date:(NSDate*)date1 InSameMonthWith:(NSDate*)date2{
NSDateComponents*comps1 =[self.calendarcomponents:(NSMonthCalendarUnit)fromDate:date1];
NSDateComponents*comps2 =[self.calendarcomponents:(NSMonthCalendarUnit)fromDate:date2];
return comps1.month== comps2.month;
}
#pragma mark -时间格式化NSDate->2012-02-02
-(NSString*)senselFormatDate:(NSDate*)date{
int year =[selfyear:date];
int mouth =[selfmonth:date];
int day =[selfday:date];
NSString* dateString =[[NSStringalloc]initWithFormat:@"%.2d/%.2d/%.2d",year,mouth,day];
return[dateString autorelease];
}
-(NSString*)HMS:(NSDate*)date{
int hour =[selfhour:date];
int minute =[selfminute:date];
int second =[selfsecond:date];
NSString* hmss =[[NSStringalloc]initWithFormat:@"%.2d:%.2d:%.2d",hour,minute,second];
return[hmss autorelease];
}
-(NSString*)formatDate:(NSDate*)date{
int year =[selfyear:date];
int mouth =[selfmonth:date];
int day =[selfday:date];
NSString* dateString =[[NSStringalloc]initWithFormat:@"%.2d-%.2d-%.2d",year,mouth,day];
return[dateString autorelease];
}
-(int)year:(NSDate*)date {
NSDateComponents*components =[self.calendarcomponents:NSYearCalendarUnitfromDate:date];
return[components year];
}
-(int)month:(NSDate*)date {
NSDateComponents*components =[self.calendarcomponents:NSMonthCalendarUnitfromDate:date];
return[components month];
}
-(int)day:(NSDate*)date {
NSDateComponents*components =[self.calendarcomponents:NSDayCalendarUnitfromDate:date];
return[components day];
}
-(int)hour:(NSDate*)date{
NSDateComponents*components =[self.calendarcomponents:NSHourCalendarUnitfromDate:date];
return[components hour];
}
-(int)minute:(NSDate*)date{
NSDateComponents*components =[self.calendarcomponents:NSMinuteCalendarUnitfromDate:date];
return[components minute];
}
-(int)second:(NSDate*)date{
NSDateComponents*components =[self.calendarcomponents:NSSecondCalendarUnitfromDate:date];
return[components second];
}
-(BOOL)isSameDay:(NSDate*)oneDate withAnotherDay:(NSDate*)anotherDate{
int oneYear=[selfyear:oneDate];
int anotherYear=[selfyear:anotherDate];
int oneMonth=[selfmonth:oneDate];
int anotherMonth=[selfmonth:anotherDate];
int oneDay=[selfday:oneDate];
int anotherDay=[selfday:anotherDate];
if(oneYear==anotherYear && oneMonth==anotherMonth && oneDay==anotherDay){
returnYES;
}else{
returnNO;
}
}
-(NSString*)getChineseCalendarWithDate:(NSDate*)date{
NSArray*chineseMonths=[NSArrayarrayWithObjects:
@"正月",@"二月",@"三月",@"四月",@"五月",@"六月",@"七月",@"八月",
@"九月",@"十月",@"冬月",@"腊月",nil];
NSArray*chineseDays=[NSArrayarrayWithObjects:
@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",
@"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",
@"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十", nil];
NSCalendar*localeCalendar=[[NSCalendaralloc]initWithCalendarIdentifier:NSChineseCalendar];
unsigned unitFlags =NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit;
NSDateComponents*localeComp =[localeCalendar components:unitFlags fromDate:date];
NSString*m_str =[chineseMonths objectAtIndex:localeComp.month-1];//月
NSString*d_str =[chineseDays objectAtIndex:localeComp.day-1];//日
NSDateFormatter*dateFormatter =[[NSDateFormatteralloc]init];
//设定时间格式,这里可以设置成自己需要的格式
[dateFormatter setDateFormat:@"yyyy年MM月dd日"];
NSString*currentDateStr =[dateFormatter stringFromDate:[NSDatedate]];
NSString*chineseCal_str =[NSStringstringWithFormat:@"%@ 农历%@%@",currentDateStr,m_str,d_str];
[localeCalendar release];
[dateFormatter release];
return chineseCal_str;
}
-(NSString*)getMemoryLunarShow{
NSArray*chineseMonths=[NSArrayarrayWithObjects:
@"正月",@"二月",@"三月",@"四月",@"五月",@"六月",@"七月",@"八月",
@"九月",@"十月",@"冬月",@"腊月",nil];
NSArray*chineseDays=[NSArrayarrayWithObjects:
@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",
@"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",
@"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十", nil];
NSArray* weeks =[NSArrayarrayWithObjects:@"周日",@"周一",@"周二",@"周三",@"周四",@"周五",@"周六",nil];
NSDate* today =[selfgetLocaleDate];
NSCalendar*localeCalendar =[[NSCalendaralloc]initWithCalendarIdentifier:NSChineseCalendar];
unsigned unitFlags =NSYearCalendarUnit|NSMonthCalendarUnit| NSDayCalendarUnit;
NSDateComponents*localeComp =[localeCalendar components:unitFlags fromDate:today];
NSString*m_str =[chineseMonths objectAtIndex:localeComp.month-1];//月
NSString *d_str = [chineseDays objectAtIndex:localeComp.day-1];//日
int month = [selfmonth:today];
int day =[selfday:today];
int weekNum=[selfdayOfWeekForDate:today];
NSString* week =[NSStringstringWithFormat:@"%@",[weeks objectAtIndex:weekNum-1]];
return [NSStringstringWithFormat:@"农历%@%@ %d月%d日(%@)",m_str,d_str,month,day,week];
}
@end